Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is happening because Ajax requests are handled <strong>asynchronously</strong>. Basically, other parts of your code will run while the request is being handled. If you have a function that is dependent on the response, put it in the callback. This will ensure that the function isnt called before the request has been completed because that call back will only be run once the request has been satisfied (<code>readyState == 4</code> and <code>status == 200</code>). It looks like this:</p> <pre><code> xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) { proceedDiv.innerHTML = xmlhttp.responseText if(xmlhttp.responseText == "You may continue.") correctData = true else correctData = false calledSecond() } } </code></pre> <p><strong>EDIT:</strong> Since it seems that you're confused about how asynchronous events work, I'll give you a brief rundown. Asynchronous events are different from regular events in that they are not subject to the program's flow. What that means is that they are executed totally independent of other events. This can be done for various reasons, but with AJAX, one reason is because it can take a long time waiting for the proper HTTP response and its much more efficient to run other things that are not dependent on that response while simultaneously waiting for the response. You have to be especially careful when doing asynchronous programming, because <strong>YOU CAN NEVER ASSUME THAT THE ASYNCHRONOUS EVENT WILL BE HANDLED BEFORE THE NEXT EVENT IN YOUR PROGRAM HAPPENS</strong>. If you have something that is dependent on the result of the asynchronous event, you must place that in the callback that is called once the asynchronous event is done. Hope this clarifies some things.</p>
 

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