PHP AJAX Example

In this tutorial, we are using PHP as a server-side programming language. In the below example, you will find a button. When you click on the button, a browser sends a request to a server using AJAX and then displays the response received from the server.

Example.html

When you click on Show Details button, fetch() function will be called. In the fetch() function, we have return AJAX coding. Once we get the response from the server, we displayed it in the div element having id equal to mobiles.

<!DOCTYPE html>
<html>
   <head>
      <script>
         function fetch(){
	    var request = new XMLHttpRequest();
	    request.onreadystatechange = function(){
	       if(this.readyState == 4 && this.status == 200){
	          var response = this.responseText;
		  document.getElementById("mobiles").innerHTML=response;
	       }
            };
            request.open("GET", "/ajax/details.php", true);
	    request.send();
         }
      </script>
   </head>
   <body>
      <button onclick="fetch()">Show Details</button>
      <div id="mobiles"></div>
   </body>
</html>

details.php

<?php
   echo "Name: Samsung Galaxy J7"."<br />";
   echo "Price: 15500"."<br />";
   echo "Features: "."<br />";
   echo "Screen Size: 5.5"."<br />";
   echo "Operating System: Android 6.0"."<br />";
?>

Output