Get variable after ajax execution

I have this code to query my server:

function myAjaxCheck(token) {
        $.ajax({
            type: 'POST',
            url: 'auth.php',
            data: {
                token: token,
            },
            dataType: 'json',
            success: function (data) {
                if (data.auth == 'OK') {
                    alert ('ok');
                    }
                } else {
                    alert('Error: ' + data.auth);
                }
            }
        }).done(function (data) {
            return data;
        });
    }

So, I need to pass the returned data to a type variable:

Var MyVariable = myAjaxCheck(token);
console.log(MyVariable);

on the console:

undefined

Where is the problem, it is assumed that the data will be returned when it is done, but it is not.

+3
source share
3 answers

By default, the request ajax()is asynchronous, so the call ajax()usually returns before the request completes. Instead, you can use the callback function.

function myAjaxCheck(token, callback) {
        $.ajax({
            type: 'POST',
            url: 'auth.php',
            data: {
                token: token,
            },
            dataType: 'json',
            success: function (data) {
                if (data.auth == 'OK') {
                    alert ('ok');
                    }
                } else {
                    alert('Error: ' + data.auth);
                }

                callback(data);
            }
        });
    }

var myVariable; 
 myAajxCheck(token, function(returnedData){ //anonymous callback function
    myVariable = returnedData;
    console.log(myVariable);
 });

If absolutely necessary for you, you can use async: falseinside a callajax() .

+7
source

See Pending completion of $ .post .

, . , undefined, , , AJAX.

0

Because you expect an immediate return value. You are using an asynchronous XHR, so the function will return ( undefinedin this case) before the XHR can complete and return its value.

0
source

All Articles