Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The third parameter in <code>xmlhttp.open("GET",url,false);</code> is whether or not to send the request asynchronously. Since you put false, it will run synchronously, which is why it blocks your code.</p> <p>In order to make this asynchronous, you should change the third parameter to <code>true</code> and then add assign a function to <code>xmlhttp.onreadystatechange</code> that will be a callback for the async request (do this before you call <code>.send()</code>.</p> <p>Another important thing to consider is that since this is asynchronous, you don't want to return a value from your ajax request, as you'll have something waiting for that return value, which means it either won't get the return value, or you have to block everything and we're back to the original problem. So consider what it is that you want to "do" with ajax response. You can either directly code this into whatever you assign to <code>xmlhttp.onreadystatechange</code>, or alternatively you can pass a callback into it using a closure, e.g.</p> <pre><code>function initRequest(url, callback) { ... xmlhttp.open("GET",url,true); xmlhttp.onreadystatechange = (function(cb) { return function() { if(xmlhttp.status &gt;= 200 &amp;&amp; xmlhttp.status &lt; 300)// 2xx is good enough { cb(xmlhttp.responseText.split("|")); } }; )(callback); xmlhttp.send(null); } </code></pre> <p>Then wherever you're calling <code>initRequest</code>, define a function that will do something with the result, and then pass it in as the second parameter, e.g.</p> <pre><code>var logResult = function(result) { console.log(result); }; initRequest("page.php", logResult); </code></pre> <p>Let me know if this makes sense, or if you have any questions :)</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