X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY ANGULAR XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

AJAX - Using a Callback Function


For asynchronous requests, a function should be created to check if the server response is ready.


AJAX - Creating a Callback Function

Create a callback function that will check if the response is ready to be processed.

Simply update the code from the previous chapter (the code still works in all browsers):

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

The callback function is registered via the onreadystatechange property of the XMLHttpRequest object.

Three important properties of the XMLHttpRequest object when using a callback function:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds the status of the server's response. Changes value from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found


Server Response

To get the response from a server, we use the responseText or responseXML property of the XMLHttpRequest object.

The following code updates the innerHTML of the div section with the data returned from the server:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

The response from the server can be a string or XML:

Property Description
responseText get the response data as a string
responseXML get the response data as XML data



Complete Example

<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
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>

Try it yourself »


Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB HOSTING

UK Reseller Hosting

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates FREE Website Templates Free HTML Templates

SHARE THIS PAGE

facebook