Where's your data variable? Is it defined?
Variable outside ajax request
I want the result of ajax outside the ajax function. My code is below :
var result;
$.ajax({
type: "GET",
url: append_url,
datatype: "json",
success: function(data){
result = data;
alert(result);
}
});
alert(result); // outputs undefined
To operate result variable outside the ajax request you can set additional param async to $.ajax()
var result;
$.ajax({
type: "GET",
url: append_url,
datatype: "json",
async: false,
success: function(data){
result = data;
console.log("Inside ajax: "+result);
}
});
console.log("Outside ajax: "+result); // fires only after the ajax request is completed
But it's really a bad practice to prevent asynchronous code in js.
What I'd suggest is to work with result inside the callback you assign to success property. That's the right way. To avoid making it a mess, just put callback into a function:
function myCallback(response) {
result = response;
console.log("Inside ajax: "+result);
// Do whatever you need with result variable
}
$.ajax({
type: "GET",
url: append_url,
datatype: "json",
success: myCallback,
});
To avoid 'callback hell' in case you're going to make more asynchronous things inside other asynchronous ones, use should utilize Promises to organize code and make it more readable as it'll look like synchronous.
Please or to participate in this conversation.