jQuery AJAX: return value on success [duplicate]

Solution 1:

You'd better change your approach to reflect an asynchronous nature of AJAX request.

Using callback function

function ChatServerQuery(data, callback) {
    $.ajax({
        url:  'chat/backend/',
        type: 'POST',
        data: data,
        success: callback
    });
}

Then you would use it:

ChatServerQuery(dataObject, function(data) {
    // work with your data came from server
});

Using promise object

$.fn.ajax returns object implementing Promise iterface, so you can use it like this:

function ChatServerQuery(data) {
    return $.ajax({
        url:  'chat/backend/',
        type: 'POST',
        data: data
    });
}

ChatServerQuery(dataObject).done(function(data) {
    // work with your data came from server
});

This option offers you more flexibility.

Solution 2:

I answered something similar earlier:

  • Why can't change the value from inside Jquery $.post function (JavaScript)

Your function returns result long before the AJAX callback executes. Anything that depends on the result of the request has to happen in or after the callback.