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.
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
asyncoption tofalse(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: