Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your function should <em>always</em> be returning before your ajax request to the PHP page completes, because the ajax request is <em>asynchronous</em>. You <em>start</em> it in your function, but it completes after the network operations are done. <code>.post</code> doesn't block waiting for the result.</p> <p>You can make it block by using <code>.ajax</code> rather than <code>.post</code> with the <code>async: false</code> option, but on many browsers that locks up the UI in an unpleasant way during the network request.</p> <p>Instead, have your function accept a callback that it will call with the result of the operation:</p> <pre><code>function checkAvailability(callback) { var grpname = $('#groupname').val(); //use ajax to run the check $.post("checkGroupName.php", { gname: grpname }, function(result){ if(Number(result) == 0){ //show that the groupname is available $('#username_availability_result').html(grpname + ' is Available'); callback(true); } else{ //show that the groupname is NOT available $('#username_availability_result').html(grpname + ' is already taken'); callback(false); } }); } </code></pre> <p>Code that used to do this:</p> <pre><code>doSomething(); if (checkAvailability()) { itsAvailableLetsDoSomething(); moreAvailableStuff(); } else { itsNotAvailableDoSomethingElse(); otherStuff(); } </code></pre> <p>...would instead look like this:</p> <pre><code>doSomething(); checkAvailability(function(available) { if (available) { itsAvailableLetsDoSomething(); moreAvailableStuff(); } else { itsNotAvailableDoSomethingElse(); otherStuff(); } }); </code></pre> <p>As you can see, the impact is minimal, but by doing this you're taking advantage of asynchronous communication to keep your UI responsive.</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