Menu Search Me

How Does AJAX Work?


To know how AJAX works, let's take a look at the following example. In this example, when you click the "change content" button, the HTML text enclosed by <div id="myDiv"> tag will be replaced by the content of the text file http://<your host>/ajax_info.txt. I have put comments in the code to explain what each part of the code does so it is very self-explanatory.

<!DOCTYPE html>
<html>
<head>
<script>

//This function will be called when the user clicks the "change content" button
function loadXMLDoc()
{
var xmlhttp;

//This is to get the built-in xmlhttp object
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

//This is to define and register a callback function that
//will change the content of the HTML text with the HTTP response, when it has arrived:
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

//This is to send an HTTP request to the server to get the ajax_info.txt file
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}

</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>