How to return data from an AJAX success event to an external function?

I need the check_membership () function below to return AJAX data. However, the "result" continues to be set on the XHR object, and not on the returned JSON object.

How to fix it?

function check_membership() {

    var result;

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

    return result;

}

Thank.

+3
source share
3 answers

Javascript "" $.ajax , , . Jax-, async false ( ), , . , , , . :

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);
        }
    });
}
+2
var result = 
{
   ajax: function(){
        jQuery.ajax({
        type: 'POST',
        url: '/ajax/member',
        dataType: 'json',
        async: false,
        success: function(data) {
                return data.signedIn;
        }
     });
   }  
}

result.ajax();

+1

You can use the 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;
}
0
source

Source: https://habr.com/ru/post/1758072/


All Articles