JavaScript function that returns AJAX call data [duplicate]

You can't return data returned by an AJAX call unless you want to call it synchronously (and you don't – trust me). But what you can return is a promise of a data returned by an AJAX call and you can do it actually in a very elegant way.

(UPDATE: Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)

Basically you can return the return value of your $.ajax(...) call:

function checkUserIdExists(userid){
    return $.ajax({
        url: 'theurl',
        type: 'GET',
        cache: false,
        data: {
           userid: userid
        }
    });
}

and someone who calls your function can use it like this:

checkUserIdExists(userid).success(function (data) {
    // do something with data
});

See this post of mine for a better explanation and demos if you are interested.


you can pass in a callback function:

function checkUserIdExists(userid, callback) {
    $.ajax({
        ...
        success: callback
    });
}

checkUserIdExists(4, function(data) {

});

With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
    .success(function() { alert("success"); })
    .error(function() { alert("error"); })
    .complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

Source


As of jQuery 1.8, the "success", "error" and "complete" callback are deprecated. Instead you should be using "done", "fail" and "always".

So you could have:

function checkUserIdExists(userid, callback) {
        return $.ajax({
        url: 'theurl',
        type: 'GET',
        cache: false,
        data: {
           userid: userid
        }
    })
    .done(callback)
    .fail(function(jqXHR, textStatus, errorThrown) {
        // Handle error
    });
}

checkUserIdExists(2, function(data) {
    console.log(data); // Do what you want with the data returned
});