AJAX Using a Callback Function


A callback function is a function passed as a parameter to another function. If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task. The function call should contain the URL and what to do on onreadystatechange (which is probably different for each call):

Let AJAX change this text.


The HTML form is given below:

<html>
 <body>
  <div id="myDiv"><h3>Let AJAX change this text</h3></div>
  <button type="button" onClick="myFunction( )">Callback</button>
 </body>
</html>

It calls the function myFunction as below when the button is clicked:

<script type="text/javascript">
  var xmlhttp;
  function myFunction( ) {
    loadXMLDoc( "ajax_info.txt",
      function( ) {
        if ( ( xmlhttp.readyState == 4 ) &&
             ( xmlhttp.status     == 200 ) ) {
          document.getElementById("myDiv").innerHTML =
            xmlhttp.responseText;
        }
      }
    );
  }
  function loadXMLDoc( url, cfunc ) {
    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 = cfunc;
    xmlhttp.open( "GET", url, true );
    xmlhttp.send( );
  }
</script>