Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since you cannot possibly tell when the ajax response from the server is arriving, AJAX is asynchronous by default. This means that the <code>$.ajax</code> get's triggered and then the javascript engine continues to execute the rest of your code (in your example the two <code>console.log</code>s outside the ajax call). Somewhere in the future, the ajax call may (or may not) get the response from the server (and notifies this by changing it's state). At this point the javascript engine will process the so called "callback" function - code which shall be executed when the ajax call is finished. You define your callback function as the <code>success</code> parameter of the ajax method.</p> <p>That's why the correct way to execute your code is to run everything which depends on the result in the callback function. Put everything directly in there, or declare a separate function which you then can invoke in the success function:</p> <pre><code>$.ajax({ /*...*/, success : function (data) { array['name'] = data['name']; array['color'] = data['color']; /* either put all your dependent code here */ /* or just call a callback function: */ callback(data); } }); /* code to be executed after the ajax call */ function callback(data){ // work with the response here console.log(data); } </code></pre> <p>Bad idea ahead:</p> <p>Alternatively you could tell the call to be synchronously (which is bad, because your browser basically is frozen while it waits for the answer from the server) and keep your code as it is.</p> <pre><code>$.ajax({ /*...*/, async : false, }); // risk some waiting time (possibly the full duration of a timeout!!) // the browser is locked during this time // continue normally console.log(array['name']); console.log(array['color']); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload