I am very new to all of this, I am tying to learn Ajax as well as Javascript, I am getting the value from a php file, but when I try to return the value in the method I get a undefined value which i log in the console., I am after trying a lot of thing but with no success. Can some one please educate me on this. And please criticize me code im sure there is a lot of bad practice.
Thanks
function checkEmail(){
var xhttp;
var status;
xhttp = new XMLHttpRequest();
var email = document.getElementById('email2').value;
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlResponse = xhttp.responseText;
status = xmlResponse;
}
};
xhttp.open("GET", "php/ajaxCom.php?email="+email, true);
xhttp.send();
return status;
}
<?php
include 'base.php';
$status;
$email_in_use = $_GET['email'];
$query = mysqli_query($link, "SELECT * FROM users WHERE email='".$email_in_use."'");
if(mysqli_num_rows($query) > 0){
$status = "false";
}else{
$status = "true";
}
echo $status;
?>
This is where I call the checkEmail
function getStatus(field, name, value) {
var status = null;
if (!field.attr('required')) return null;
if (!value) status = 'Please fill out the required field: ' + name;
else if (emailField.test(name) || emailField.test(field.attr('type'))) {
var b = checkEmail();
console.log(b);
if (!emailValue.test(value)) {
status = 'Please enter a valid email address for: ' + name;
}else if ( b == "false"){
alert("im here");
status = 'Please enter a valid email this email already has an acount';
}
}
return status;
}
update
The stats alert is shown correctly but the console log is still showing undefined
function getStatus(field, name, value) {
var status = null;
if (!field.attr('required')) return null;
if (!value) status = 'Please fill out the required field: ' + name;
else if (emailField.test(name) || emailField.test(field.attr('type'))) {
var b;
checkEmail(function(status) {
alert('Status: ' + status);
b = status;
});
console.log(b);
if (!emailValue.test(value)) {
status = 'Please enter a valid email address for: ' + name;
}else if ( b == "false" || b == "true"){
alert("im here");
status = 'Please enter a valid email this email already has an acount';
}
}
return status;
}