1

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;
}
1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You can turn off asynchronous requests if that is what you really want: api.jquery.com/jQuery.ajax , look for the setting 'async'.
async: false often hangs the browser till the server response
@row1: Synchronous, I suppose "JAX", requests are in general not a good idea.
Use of synchronous requests is discouraged, since it blocks everything in your webpage and it seems to the user that it's frozen, which might result in your application being closed. Use with extreme caution, or better, don't use at all.
@FelixKling Sure it is generally not a good idea. But if your service is guaranteed to return in a small amount of milliseconds then it might be useful (simpler) going down the more procedural path.
3

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);
});

1 Comment

Thanks a lot. This is the solution I've been searching for :)
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.