I want assign to a global variable, JSON data retrieved from an AJAX request. Here is my code:
var ajaxData = "blabla";
$.ajax({
url: "url.php",
dataType: "json",
data: {
action: "searchResultsCallback",
termId: 5
},
success: function(data) {
ajaxData = data;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
})
console.log(ajaxData);
Now, in the $.ajax
function I changed ajaxData
from blabla
to whatever the value of data
is. But, instead, in the console, the output I get is:
blabla
XHR finished loading: GET "url.php?action=searchResultsCallback&termId=523".
So it seems like the browser prints the value of ajaxData
first, and then executing the ajax request. More than that. if I change the success
option to be like this:
success: function(data) {
ajaxData = data;
console.log(ajaxData);
},
Then I DO get the data retrived from the ajax request!
blabla
XHR finished loading: GET "url.php?action=searchResultsCallback&termId=523".
[Object, Object, Object, Object, Object]
Why is that? How can I fix it?