What is the Ajax callback function?

When you make an Ajax call, you may want to do something when the response is received. This is where the Ajax callback function comes in. The callback function is a function that is executed when the Ajax call is completed. The callback function is passed two parameters: the response from the Ajax call and the status of the Ajax call.

The callback function should be defined as a function and not as a property of an object. Here is an example of a callback function:

function callback(response, status) {
    if (status === "success") {
    // Do something with the response
}
}

The callback function can be defined as a property of an object, as shown in the following example:

var obj = {
    callback: function(response, status) {
        if (status === "success") {
        // Do something with the response
        }
    }
}

However, this is not recommended, as the function may be called more than once.

You can also define the callback function as a property of the XMLHttpRequest object. Here is an example:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        callback(xhr.response, xhr.status);
    }
}

xhr.open("GET", "https://www.example.com/");
xhr.send();

The callback function can also be defined as a property of the jQuery object. Here is an example:

$(document).ready(function() {
        $.ajax({
        url: "https://www.example.com/",
        type: "GET",
        dataType: "json",
        success: function(response) {
        console.log(response);
    },

    error: function(xhr, status, err) {
   		 console.log(status, err);
    }
	});
});

The callback function is also available as a property of the global window object. Here is an example:

window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
        callback(xhr.response, xhr.status);
    }
}

xhr.open("GET", "https://www.example.com/");
xhr.send();
}

The callback function can also be defined as a property of the global jQuery object. Here is an example:

$(document).ready(function() {
    $.ajaxSetup({
        ajax: {
            url: "https://www.example.com/",
            type: "GET",
            dataType: "json",
            success: function(response) {
            console.log(response);
        },

        error: function(xhr, status, err) {
                console.log(status, err);
            }
        }
    });
});
💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.