Skip to content Skip to sidebar Skip to footer

Jquery: $.ajax Success Callback Doesn't Let Me Assign To Outside Private Variable

var doCheck = function() { var data; $.ajax({ url: 'check.php', data: 'ch=check', success: function(resp) { data = resp; }

Solution 1:

Ajax is asynchronous. Which is why you have to organize your logic with callbacks:

var doCheck = function(callback) {
    var data;

    $.ajax({
        url: 'check.php',
        data: 'ch=check',
        success: function(resp) {
            callback(data == 1);
        }
    });
};

doCheck(function(result) {
    // result is true or false
});

Solution 2:

Place the 'console.log(data)' sentence after 'data=resp'. Probably it is executing before the success method and becuase this it has no value set.

Solution 3:

It takes time till you get the response, so the console.log() comes when the data isn't set yet

Solution 4:

This is because the ajax Request by default is asynchronous, however instead of making it synchronous, I'd suggest redesigning you're approach.

Solution 5:

Ajax stands for Asynchronous JavaScript and XML. data is being set after the call to the server returns, and only if the call was sucessfull.

The console.log is happening immediatly after sending the async request off, before the sucess has a chance to run.

Post a Comment for "Jquery: $.ajax Success Callback Doesn't Let Me Assign To Outside Private Variable"