2

I have a problem passing data from a JQuery ajax call back to the calling location. The code in question is below:

jQuery("#button").click(function()
{   
    for(var i = 0;i < data.length; i++)
    {
        result = updateUser(data[i]); //result is not populated..
                    alert(result); //prints 'undefined'

    }
});

function updateUser(user_id)
{       
    jQuery.ajax({
        url:"/users/update/"+user_id,
        type:"GET",
        async: false,
        success: (function(data){           
            //if I alert "data" here it shows up correctly
                            //but if i try to return it like below 
                            //it does not get passed correctly 
                            return data; 
        })
    });

Any pointers are greatly appreciated

1

5 Answers 5

5

You cannot return value from an AJAX success handler like that. AJAX is asynchronous so execution will proceed to the next line where result is undefined. The only way you can get data back from an asynchronous operation is to use a callback. A callback is a function that gets called when the asynchronous operation finishes what it is doing:

jQuery("#button").click(function () {
    for (var i = 0; i < data.length; i++) {
        updateUser(data[i], function(result) {
            alert(result);
        });
    }
});

function updateUser(user_id, callback) {
    jQuery.ajax({
        url: "/users/update/" + user_id,
        type: "GET",
        success: callback
    });
}

Here, you're calling the callback in the success handler of the AJAX call and so now you have access to the data that was returned by the AJAX call.

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

14 Comments

pretty dang similar to mine :P beat you to the punch by like 10 seconds
Why the downvote? If you're going to downvote at least explain why.
1. because you've forced it to be synchronous, 2. because it doesn't use the Deferred pattern for handling this scenario. 3. you might as well just have said success: callback without the extra closure.
wasn't me -_-, but someone doesn't like my answer either and no explanation
i just learn how we can use call back thank you @VivinPaliath
|
1

Have your function return the result of calling jQuery.ajax() - this object implements the jQuery deferred promise interface. That is, an object that promises to return a result some time later.

function updateUser(user_id) {       
    return jQuery.ajax({...});
}

and then use .done() to register the function to be called when the promise gets resolved:

updateUser(data[i]).done(function(result) {
    alert(result);
});

The important part is that deferred objects allow you to complete decouple the initiation of the asynchronous task (i.e. your updateUser function) with what's supposed to happen when that task completes (or fails).

Hence there's no need to pass any callback functions to .ajax, and you can also chain your call with other deferred objects (e.g. animations, other AJAX requests).

Furthermore, you can register as many .done() callbacks as you like, and .fail() callbacks too, without ever having to change updateUser().

Comments

1

The A in ajax is Asynchronous, which means that when the file loaded, the function that started it is done running. Try using jQuery Deferred: http://api.jquery.com/category/deferred-object/

Example:

jQuery("#button").click(function()
{   
    for(var i = 0;i < data.length; i++)
    {
        updateUser(data[i]).done(function(result) {
                    alert(result); //prints 'undefined'
        });

    }
});

function updateUser(user_id)
{
    return jQuery.ajax({
        url:"/users/update/"+user_id,
        type:"GET",
        async: false,
        success: (function(data){           
            ...
        })
    });
}

4 Comments

close, except that there's no need to create a new Deferred object - the $.ajax() function creates one for you.
Worked like a charm thanks Steve, @Alnitak How can I use the Deferred object from the jQuery.ajax() function without creating a new Deferred object?
@raphie just eliminate the defer variable in this answer and chnage the function so it does return jQuery.ajax(...).
Thanks @Alnitak, Appreciate the input. This allowed me to use PHP session variables in Javascript, been trying to do that for couple of days with no success.
0

The function that called the success function is the Ajax request and not the UpdateUser function. So obviously when you return it it will return back from the success callback but not to the UpdateUser function..

Also since the ajax is Asynchronous , buy the time the callback is executed it will come out of the UpdateUser function.. !

Comments

-2

pretty sure what is happening (not an expert) but you are returning 'data' for your annonomys function in success and not your whole updateUser function

function updateUser(user_id)
{       
    var retData;
    jQuery.ajax({
        url:"/users/update/"+user_id,
        type:"GET",
        async: false,
        success: (function(data){           
            //if I alert "data" here it shows up correctly
                            //but if i try to return it like below 
                            //it does not get passed correctly 
                            retData = data; 
        })
    return retData;
});

But like i said, i am no expert.

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.