I am facing problems passing an email address to a php file through AJAX. The code I am using is pretty basic but I can't seem to get it to work. Could anyone help me understand what's going wrong? I amd pretty new to Ajax (about 2 days old) so please forgive me if this seems pretty lame.
function emailchk () {
if (!document.getElementById("email").value) {
document.getElementById("emailmsg").innerHTML = " ";
}
else {
url = "emailchk.php?email=" + document.getElementById("email").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = showEmailContents;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("Sorry, but I couldn't create an XMLHttpRequest");
}
return false;
}
}
function showEmailContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("emailmsg").innerHTML = outMsg;
if (outMsg == "Email already exists") {
document.getElementById("validate").value = "no";
}
else {
document.getElementById("validate").value = "yes";
}
}
}
The PHP file is also pretty basic...
<?php
include ("dbconfig.php");
$sql = "select name from users where email = '$_POST[email]'";
$result = mysql_query ($sql, $conn) or die ("could not query database");
if (mysql_num_rows($result)) {
print "Email already exists";
}
else {
print "Email is available";
}
?>
Thanks in advance...