peter.o
peter.o

Reputation: 3530

Save response from jQuery ajax function

I've got a custom function, which calls ajax request and I'm able to save response data to variable and return it. 0 is always returned, but alert shows e.g. 3712.

Here is the function:

function getNo(index, val) {

var $ret = 0;

$('body').showLoading();
$.ajax({
    type: 'POST',
    url: BASE_URL + 'tools/no.php?id='+index+'&value='+val,
    data: $("#form").serialize(),
    cache: false,
    success: function(data) {
        $('body').hideLoading();
        alert('data: ' + data);
        $ret = data;
    }
});
return $ret;
}

Upvotes: 1

Views: 15665

Answers (3)

Moe Sweet
Moe Sweet

Reputation: 3721

Because "A" in Ajax stands for Asynchronous, return $ret; is executed before the Ajax call finds it's way back to success function.

Rather than trying to return the value, try to call a function within the ajax success block.

success: function(data) {
    $('body').hideLoading();
    alert('data: ' + data);
    $ret = data;
doSomething(data);
}

Upvotes: 0

Abdul Munim
Abdul Munim

Reputation: 19217

This will return ZERO because of the asynchronous call. Rather I would suggest you to pass a callback method to work with the response.

See an example below:

function getNo(index, val, callback) {
    var $ret = 0;

    $('body').showLoading();
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'tools/no.php?id=' + index + '&value=' + val,
        data: $("#form").serialize(),
        cache: false,
        success: function (data) {
            $('body').hideLoading();
            callback(data);
        }
    });
    return $ret;
}

//USAGE
getNo(3, "value", function (data) {
    //do something with data responded from the server
    alert(data);
});

Upvotes: 3

James.Xu
James.Xu

Reputation: 8295

because ajax is asynchronous, when return $ret; is executed, the response is not ready yet, so its initial value 0 is returned.

you have to do what you want to do in the success callback function rather than return.

Upvotes: 4

Related Questions