I have this code for make some request to 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 into a variable like:
Var MyVariable = myAjaxCheck(token);
console.log(MyVariable);
Where is the problem, is supposed to data will returned when done, but isn't.
By default, an ajax()
request is asynchronous so the call to ajax()
will usually return before the request completes. You could make use of a callback function instead.
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 you absolutely must, you could use async: false
inside the call to ajax()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With