Did you find this useful?
Socialize it today.


Ajax Callback Function

Thursday, August 02, 2012

The Ajax callback function that is normally assigned as the onreadystatechange event handler, is the one of the critical components within the Ajax block of code. The callback function is responsible for keeping a close eye on the progress of requests. The callback needs to identify the result of the request and proceed with the handling of the data returned from the web server. Callback functions generally also serve as a delegator, meaning that it will delegate the processing of other code to other areas of your JavaScript application.


Example

We will use the following HTML for the examples listed below.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  loadAjax(){
  // ... JavaScript code
  }
</script>
</head>
<body>
 <img id="img1" onclick="loadAjax()" src="go.png" /> ; 
 <div id="div1"> <!-- Some Content --> </div>
</body>
</html>


Without Callback

<script type="text/javascript">
    function loadAjax() {
    var xhr = false;
    if (window.XMLHttpRequest) {
        xhr = new window.XMLHttpRequest;
        }
        else {
              try {
                    xhr =  ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (ex) {
                    window.console.log("Ajax not supported.");
                }
            } 
        if (xhr) {
            xhr.onreadystatechange = ajax_response;
            xhr.open("GET", "demo_ajax_load.txt", true);
            xhr.send(null);
        }
        function ajax_response() {
          if(xhr.readyState == 4 && xhr.status == 200) {
              document.getElementById("div1").innerHTML = xhr.responseText;  
          }
        }
    }
</script>


In the previous example, we set an event handler for the "onreadystatechange" event as our ajax_response() function which will be executed every time the state of the request changes. By setting the onreadystatechange property of the Ajax object to this function, our function will be called every time the state of the object changes. This is not optimal. The readyState property can have several values:

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request completed and response is ready


Callback

<script type="text/javascript">
    function loadAjax() {
    var xhr = false;
    if (window.XMLHttpRequest) {
        xhr = new window.XMLHttpRequest;
        }
        else {
              try {
                    xhr =  ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (ex) {
                    window.console.log("Ajax not supported.");
                }
            } 
        if (xhr) {
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("div1").innerHTML = xhr.responseText;
                }
            }
            xhr.open("GET", "demo_ajax_load.txt", true);
            xhr.send(null);
        }
    }
</script>


In the example with the Callback function, we simplified and improved the readability of the code. Most JavaScript frameworks will encourage you to take advantage of functional programming in this manner.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Ajax for Dummies The Complete Reference Ajax Bulletproof Ajax