I have a JavaScript function used by the onblur event of a textbox. The textbox captures an email address
function strEmailUnique(strEmail, intClientID) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'AJAX_retrieval.php?strEmail=' + strEmail + '&intClientID=' + intClientID, true);
xmlhttp.send();
return xmlhttp.responseText;
}
The AJAX call returns the name of the person with that email if the email exists, otherwise it returns an empty string.
However, it doesn't work. At least, not until I insert this line
alert('xmlhttp.responseText: ' + xmlhttp.responseText);
before the return statement. I have no idea why this works - and I need to know, because obviously I don't want the alert in the live code.
When I say "it works", the actual alert when it happens indicates an empty response, but the subsequent behaviour indicates that a non-empty value is returned by the function. This too is a mystery.
I have tried accessing the response before returning it (which I figured is what the alert() is doing)
var strResponse = xmlhttp.responseText;
return strResponse;
and I also thought that it might be a timing/synchronisation issue so I tried inserting this
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > 3000){
break;
}
}
from JavaScript sleep/wait before continuing before the return, but to no avail.
My onblur event code (which I don't think is relevant) is
var strDB_outcome = strEmailUnique(document.getElementById('email').value, -1); if (strDB_outcome != '') alert('The email address ' + document.getElementById('email').value + ' is already registered to ' + strDB_outcome); "
and the AJAX target does this
echo fetch_datum($conn, "SELECT IFNULL((SELECT REPLACE(CONCAT(LEFT(strForenames, 1), '_', strSurname), ' ', '') FROM $tblClients WHERE LOWER(strEmail) = LOWER('{$_GET['strEmail']}') AND intClientID <> {$_GET['intClientID']} LIMIT 1), '')");
which again I don't think is relevant - this stuff does what I expect as long as the alert() is included in the JS function. What can I do instead of the alert() statement?
The following SO questions all seem to involve more complex scenarios
JavaScript won't work unless I use alert()!
Javascript ignores part of code unless I put an "alert" before it
Form fields not populated from AJAX unless I include an alert in the code
or very specific fixes.