|
 
Using XML: A PHP Developer's Primer, Part 2
Adam Delves
Processing the Data
We use a switch statement on the
action variable to carry out the
required action and get a true or false response. This is stored in a
variable called $ret which we return to the Ajax application to
indicate success or failure.
PHP:
$data =
'';
switch ($action) {
case
'validate':
$ret = validate_email($email);
$data = (string) $email->getId();
break;
case
'verify':
try
{
$ret = $email->verify(@$_GET['v_code']);
}
catch (EmailValidatorException
$e) {
/* the email has not been
validated - validate it now */
$action = 'validate';
$ret = validate_email($email);
}
$data = (string) $email->getId();
break;
case
'unknownerror':
$ret = 0;
break;
default:
//fail
$action = 'invalid';
$ret = 0;
}
function
validate_email(EmailValidator $email)
{
/* validate the email */
if(! $email->validate()) {
return
false;
}
$email->save(); // save it to the database
$email->sendVerificationEmail(); // send the verification
email
return true;
}
Again, notice how we modify the
action variable and instead validate the email address if
verification fails. If the email turns out to be valid, the
sendVerificationEmail method is called. This causes the EmailValidator
to generate a random 5 character verification code and send it in an
email to the supplied email address.
Returning a Response
The response sent back to the Ajax engine is not like a normal response
which is sent as HTML. We return the response as plain text in the form
of a semi-colon delimited string containing three fields:
status;data;context
- status – set to 1 if the request was successful
and 0 if the
request was unsuccessful
- data – this contains the email ID generated by
the
EmailValidator class
- context – this is set to the value of the action
variable. It
is usually the same as value passed by the Ajax engine but may change
if the email has been revalidated or an error occurred. The context is
used by the Ajax engine to decide how to respond.
We generate the response by joining the $ret, $data and $action
variables together with semi-colons.
PHP:
/* send the
response as
plain text */
header('Content-Type: text/plain');
echo((int) $ret
. ';' . $data . ';' . $action);
The HTML Code
The HTML code itself contains
only a link to the script containing the
Ajax engine. This ensures that the script is only downloaded if the
browser supports Javascript. The HTML code itself produces a fully
functioning HTML form which does not require Ajax. If Ajax is not
enabled the script receiving the form data will process and validate
the email address normally.
HTML:
<!DOCTYPE
html
PUBLIC "-//W3C//DTD
XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="en" lang="en">
<head>
<title>Ajax
Email Validation</title>
<script src="ajax_validation_engine.js"
type="text/javascript"></script>
</head>
<body onload="init();">
<h1>AJAX
Email Validation</h1>
<p>The form below demonstrates how to use
AJAX
to validate an email while the user is filling
out a form. Fill in
the form below for a demo:</p>
<div>
<form id="formEmail" action="input.php" method="post">
<div>
<div id="emailMsg" style="display:none"></div>
<label for="txtEmail">Email
Address: </label>
<input type="text" id="txtEmail" name="email"
/>
<span id="verify"
style="display:
none"><br />
<span id="verifyMsg"></span><br
/>
<label for="txtVerify">Verification
Code: </label>
<input id="txtVerify" type="text" name="v_code"
/>
<input type="hidden" name="email_id" value="" />
<button id="btnVerify" onclick="verifyAddress(); return
false;">Verify</button>
</span>
</div>
<div>
<label for="txtFirstName">First
Name: </label>
<input type="text" id="txtFirstName"
name="fname"
/>
</div>
<div>
<label for="txtLastName">Last
Name: </label>
<input id="txtLastName"
type="text" name="sname"
/>
</div>
<p>A Little about yourself:<br
/><textarea cols="20" rows="10" name="bio"></textarea></p>
<p><input id="btnSubmit" type="submit"
/></p>
</form>
</div>
</body>
</html>
The Ajax Engine
The Ajax engine responds to
events in the user interface and
initializes communication with the server-side script. It also
responds to the return data from the server-side script and takes the
appropriate action based on the response.
Creating an instance of the
XMLHTTP Object
The method used to create an
instance of the XMLHTTP object depends on the browser being used. While
Firefox and Netscape expose the XMLHttpRequest object, Internet
Explorer exposes several different versions of the MSXML ActiveX control
that depends on the version of Internet Explorer that is being used. The
getXMLHTTP function determines which method is supported (if any) and
creates an instance of the appropriate object. If it fails, it returns
false.
Javascript:
function getXMLHTTP()
{
if ((typeof XMLHttpRequest)
!= "undefined")
{
/* XMLHTTPRequest present,
use that */
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
/* there are
several versions of IE's Active X control, use the most recent one
available */
var xmlVersions =
["MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0",
"MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp",
"Microsoft.XMLHTTP"];
for (var x = 0; x <
xmlVersions.length; x++) {
try {
var xmlHTTP
= new ActiveXObject(xmlVersions[x]);
return xmlHTTP;
} catch (e)
{
//continue
looping
}
}
}
/*
if none of that worked, return false, to
indicate failure */
return false;
}
Initializing the Environment
The HTML page which contains the
form loads originally without any
Javascript. This ensures that it is fully functional without Ajax. The
init function initializes the Ajax environment by creating an instance
of the XMLHTTP object and setting up all of the global variables. Most
importantly, if we cannot create an XMLHTTP object, we exit the
function and allow the user to continue filling out the form without
Ajax. This fall back feature is very important, as the likely result of telling
a user that they cannot signup to your site until they enable Javascript
will be the user going elsewhere (and not returning).
Javascript:
var xmlHTTP;
var theForm;
var btnSubmit;
var txtEmail;
var verify;
var verifyMsg;
var txtVerify;
var btnVerify;
var emailMsg;
var emailValidate;
function init()
{
/*
close the document output*/
document.close();
xmlHTTP
= getXMLHTTP();
if (! xmlHTTP) {
/* do not
continue if XML HTTP is not available */
return;
}
/*
initialize global variables */
theForm
= document.getElementById('formEmail');
btnSubmit
=
document.getElementById('btnSubmit');
txtEmail
=
document.getElementById('txtEmail')
verify
=
document.getElementById('verify')
verifyMsg
=
document.getElementById('verifyMsg');
txtVerify
=
document.getElementById('txtVerify');
btnVerify
=
document.getElementById('btnVerify');
emailMsg
=
document.getElementById('emailMsg');
emailValidate
= 'email_validate.php?action=';
/*
disable the submit button */
btnSubmit.setAttribute('disabled',
'disabled');
txtEmail
=
document.getElementById('txtEmail');
/*
set the onchange event of the email
input box to the validateAddress() function */
txtEmail.onchange = validateAddress;
}
|