tags:

views:

53

answers:

3

I want the check_membership() function below to return the AJAX "data". However, "result" keeps getting set to the XHR object, not the returned JSON object.

How do I fix this?

function check_membership() {

    var result;

    result = jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false,
        success: function(data) {
            return data;
        }
    });

    return result;

}

Thanks.

A: 

You can use async property to return data synchronously:

function check_membership() {
  var result = jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false
    });
 return result.SignedIn;
}
Pavel Morshenyuk
I put the alert function in there for debugging purposes. I just want check_membership() to return the AJAX "data".
JMan
oh sorry it was not clear enough. i've explained another solution in updated post. check this one.
Pavel Morshenyuk
I added "async: false" (see updated code above) and still same result.
JMan
+2  A: 

Javascript will not 'wait' for the $.ajax's success callback to fire before returning from the main function, so there's a good chance that nothing will be returned. You will have to either use a synchronous-Jax call by setting the async option to false (which will block the browser for the duration of the request) or revise your strategy, e.g. by doing what you want to ultimately get done within the success callback. For example:

function update_membership_status() {
    jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        success: function(json) {
            $("#status").text('Signed In:' + json.SignedIn + "  msg" + json.msg);
        }
    });
}
karim79
Unfortunately, this still doesn't work. Would you please take a look at my updated code above? "Result" is still set to the XHR object, not the returned JSON object.
JMan
I figured it out. See my comment above. It looks like returning data from within a callback does not behave as one would expect.
JMan
A: 
var result = 
{
   ajax: function(){
        jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false,
        success: function(data) {
                return data.signedIn;
        }
     });
   }  
}

then call result.ajax(); by whatever

fleces