</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/7779697/javascript-asynchronous-return-value-assignment-with-jquery" dir="ltr">JavaScript asynchronous return value / assignment with jQuery [duplicate]</a>
<span class="question-originals-answer-count">
(2 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2014-03-13 00:45:29Z" class="relativetime">6 years ago</span>.</div>
</div>
</aside>
I have this code in JavaScript and jQuery and I need to fix it:
function valid_form() {
val_avail_email=valid_avail_email();
if (val_avail_email!="") {
$("#email_valid").html(val_avail_email);
return false;
}
return true;
}
function valid_avail_email() {
var error="";
$.get("valid_avail_email.php",{email:document.reg_form.email_reg.value},function(output) {
error=output;
});
return error;
}
So obviously I want the error
variable to contain the output of the valid_avail_email.php
and than make the valid_avail_email()
function return that value.
Here is the code in valid_avail_email.php
:
<?php
include("config.php");
$email=$_GET["email"];
$sql="select email from users";
$sql_query=mysql_query($sql);
if (!$sql_query) {
echo mysql_error();
}
$res_assoc = mysql_fetch_assoc($sql_query);
foreach ($res_assoc as $field=>$value) {
if ($value==$email) {
echo "please use another email this one is taken ";
}
}
?>
</div>
Problem is that the $.get() function initiates an asynchronous ajax call, means, the function returns while the ajax call is still running. You have to inform the GUI from within the ajax callback function, e.g.:
$.get("valid_avail_email.php",{email:document.reg_form.email_reg.value},function(output) {
error=output;
if (error !== '')
alert('Sorry, use another email!');
});
you don't need to do a foreach loop to check if the email is in db. just do a following query:
SELECT email FROM users WHERE email = '$email'
and check if the result contains any item. this method is faster than enumerating all the emails with "foreach" loop because the db returns 1 or 0 results and not thousands if you have a big db.
your valid_avail_email() is ok.. just check in your JS if the function returns anything, if yes, there alert shows the error:
var emailOk = valid_avail_email("blabla@email.com");
if(emailOk != ""){
//the following alert will show the error from php, it can show mysql_error() or "please use another email.." message
alert(emailOk);
//do stuff to abort the script
}