I am using following method to call the php:
function validateEmaiAjax(email){
val = null;
$("#warning").load("https://localhost/Continental%20Tourism/register_ajax.php",{email: email}, function(rspns, stat, xml){
val = rspns;
});
if(val == ".")
return true;
else {
return false;
}
}
my php code is:
<?php
$dbc = mysqli_connect("localhost","root","pass","continental_tourism") OR die(mysqli_connect_error());
$email = $_REQUEST['email'];
$query = "SELECT email FROM customer_info WHERE email = '$email' ";
$r = mysqli_query($dbc, $query) OR die(mysqli_error($dbc));
if(mysqli_num_rows($r) > 0)
echo "Email address exists!";
else
echo ".";
?>
Basically this do check the database and if email exists shows "Email address exists!" if not I want to return true
(so I echo "." and compare it). The weird thing is if i put a break point using firebug near if(val == ".")
program works correctly and returns true. If I remove that break point function always return false. I cant understand why this happens. Please help! Thanks.
The reason you have this problem is because you have performed an asynchronous request. This means that the if(rspns == ".")
will be reached before the response has been received from the server, and the result will always be false
.
In order to wrap this code in a function the returns a boolean and does not require a callback function (a blocking procedure) you will need to use a synchronous request:
function validateEmaiAjax(email) {
// This is the correct way to initialise a variable with no value in a function
var val;
// Make a synchronous HTTP request
$.ajax({
url: "https://localhost/Continental%20Tourism/register_ajax.php",
async: false,
data: {
email: email
},
success: function(response) {
// Update the DOM and send response data back to parent function
$("#warning").html(response);
val = response;
}
});
// Now this will work
if(val == ".") {
return true;
} else {
$("#warning").show();
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With