2

This function wont return any value, even though the ajax call goes through correctly

Function:

function queryData(request)
{
    var ret = null;
    $.ajax({
        url: 'ajax.php',
        data: 'requestdata='+request,
        dataType: 'json',
        type: 'post',
        success: function (j) {
            if(j.ok == true)
                return j.data;
            else
                return 'error';
        }
    });
    return 'error';
}
1

4 Answers 4

3

The ajax function works asynchronously, meaning that it will execute the success function when it gets the result back from the server.

The queryData function will always return 'error' due to the nature of AJAX requests (at least performed this way). You can force the ajax requests to be done synchronously, but this is usually not the desired behavior.

You should add the logic that you want in your success function, rather than trying to return it back. You can pass a named function to the success option if you prefer that. See the jQuery documentation on ajax here.

0

You can't do that.

AJAX is asynchronous, meaning that your function will return before the server sends a response.
You need to pass the value using a callback, the way $.ajax does.

0

This function returns a value before the ajax call actually completes. An ajax call is an asynchronous operation, so when you do the $.ajax() call, it immediately returns, your function runs into the return 'error' on line 16 and returns 'error'.

A few milliseconds later the ajax call completes and your success function gets executed, but its return value is not going anywhere.

0

The success function will be called asynchronously. So first of all the function initialize the ajax request and ended with the last statement return 'error';. After that, after the receiving the response from the server the success function will be called from jQuery. It returns back to the jQuery but will not be used.

Not the answer you're looking for? Browse other questions tagged or ask your own question.