Skip to content Skip to sidebar Skip to footer

How To Create Callback Function Using Ajax?

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page. When I try this: function get_ema

Solution 1:

From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).

When you return data from the server in another function like this

function get_emailno(emailid, mailfolder) {

    $.ajax({ 
        // ajax settings
    });
    return email_number;
}

Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.

Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.

There are two ways you can define callbacks.

1. Define them within the jquery ajax request settings like this:

$.ajax({ 
    // other ajax settings 
    success: function(data) {},
    error: function() {},
    complete: function() {},
});

2. Or chain the callbacks to the returned jqXHR object like this:

$.ajax({ 
    // other ajax settings 
}).done(function(data) {}).fail(function() {}).always(function() {});

The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().

On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).

With this knowledge, you can better write your code to catch the data returned from the server at the right time.

var email_number = '';

// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
    var hash    = window.location.hash;
    var mailfolder = hash.split('/')[0].replace('#', '');
    var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
    get_emailno(emailid, mailfolder);
}

function get_emailno(emailid, mailfolder) {

    $.ajax({
        url: 'getemailnumber.php',
        type: 'POST',

        data : {
            emailid: emailid,
            mailfolder: mailfolder
        },

        success: function(data)
        {
            // sufficient to get returned data
            email_number = data;

            // use email_number here
            alert(email_number); // alert it
            console.log(email_number); // or log it
            $('body').html(email_number); // or append to DOM
        }
    });
}

Post a Comment for "How To Create Callback Function Using Ajax?"