I'm trying to write my first bit of AJAX code and I'm having some trouble making it work. Using console.log() (Firefox alternative to alert()), I see that my request object's readyState is always 0. So, the code in my conditional block is never executed. I must be doing something wrong. Can anyone tell me what's wrong? ...
JavaScript:
checkEmail.php:
Thank you.
--
-- Ghodmode
Give a man a fish and he'll come back to buy more... Teach a man to fish and you're out of business.
JavaScript:
Code:
var req;
var target;
var statusObj;
var isIE;
function initRequest() {
if ( window.XMLHttpRequest ) {
req = new XMLHttpRequest();
} else if ( window.ActiveXObject ) {
isIE = true;
req = new ActiveXObject( "Microsoft.XMLHTTP" );
}
} // End initRequest function
function validateEmail() {
target = document.getElementById( 'email' );
statusObj = document.getElementById( 'emailStatus' );
var regex = /^.+@.+\..+$/;
if ( target.value == '' ) {
statusObj.innerHTML = '<span class="required">(required)</span>';
return true;
}
if ( regex.exec(target.value) ) {
var url = 'checkEmail.php?email=' + escape( target.value );
initRequest();
req.onreadystatechange = processRequest();
req.open( 'GET', url, true );
req.send( null );
} else {
statusObj.innerHTML = '<span class="other">(invalid)</span>';
}
return true;
}
function processRequest() {
console.log( "processRequest" );
console.log( "req.readyState: %d", req.readyState );
if ( req.readyState == 4 ) {
if ( req.status == 200 ) {
var message = req.responseXML.getElementsByTagName("status")[0].childNodes[0].nodeValue;
console.log( message );
if ( message == "available" ) {
statusObj.innerHTML = '<span class="valid">Valid</span>';
} else {
statusObj.innerHTML = '<span class="other">In Use</span>';
}
}
}
} // End processRequest function
checkEmail.php:
Code:
<?php
include( 'setup.php' );
require_once( 'DB.php' );
$dbh = DB::connect( "mysql://$dbuser:$dbpassword@$dbhost/$database" );
if ( DB::isError($dbh) ) die( "Connection failure: " . $dbh->getMessage() );
$email = $_GET['email'];
$statement = "
select *
from user
where email = '$email'
";
$sth = $dbh->query( $statement );
header( 'Content-Type: text/xml' );
header( 'Cache-Control: no-cache' );
if ( $sth->numRows() > 0 ) {
echo '<status>in use</status>';
} else {
echo '<status>available</status>';
}
?>
Thank you.
--
-- Ghodmode
Give a man a fish and he'll come back to buy more... Teach a man to fish and you're out of business.