0

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?

Community
  • 1
  • 1
Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • Thats how async code works. Dont try and fix it - just call the code that requires the data **after** the success function fires. Synchronous ajax is possible, but can hang the browser so is generally to be avoided – Steve Dec 07 '15 at 14:51
  • Could you please show me how? I am not quite sure I understand. Thank you very much! – Michael Haddad Dec 07 '15 at 14:57
  • 1
    Basically, put the code that uses `ajaxData` into a function, for example `function doStuff(){//code here}` then call that once the ajax completes `success:function(data){ajaxData = data; doStuff();}` By doing that you will also see that probably you dont need a global, and can instead just pass `data` as a parameter of the function. Understanding async and callbacks is a fundamental part of JavaScript and is too large a subject to discuss in comment here – Steve Dec 07 '15 at 15:01
  • But if, for example, I want data to be in a variable so I could use it multiplt times without calling the server everytime, how should I do this? – Michael Haddad Dec 07 '15 at 15:14
  • All code that requires `ajaxData` is contained within, or called from, `doStuff` function. As that function is not called until the data is populated, you are fine. – Steve Dec 07 '15 at 15:29

0 Answers0