Computers & ProgrammingAJAXFrontend Development

AJAX Callback Function

The Ajax callback function that is normally assigned as the onreadystatechange event handler is 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.

Leave a Comment

Your email address will not be published.

Scroll to Top