#native_company# #native_desc#
#native_cta#

Using XML: A PHP Developer’s Primer, Part 2

By Adam Delves
on July 23, 2008

An Introduction to AJAX

In the first part of this series, we took a look at how PHP 5 can be used to manipulate and parse XML files. In this installment, we are going to focus on Ajax, one of the most useful and topical applications of XML.
Initially, we are going to introduce Ajax and learn how to use the XMLHTTP object provided by most modern web browsers to create a live email validation form. Then we will pick up where we left off with the theme of XML and introduce XSLT, which we will use to transform our library XML from the previous article into valid XHTML code.

What is AJAX?

There exists today a huge number of web applications that do everything from manage your photos, to mission-critical distributed systems. The majority of these applications exist in three parts.
  • The back end section is usually where the data pertinent to the application is stored. The back end may include logic which deals with the update and retrieval of this data in the form of server side code, SQL and stored procedures.
  • The middle ware section is where all the magic happens, typically transforming, manipulating, retrieving, verifying an validating the data before sending it on to the front end.
  • The front end section is what the user interacts with; it often contains very little logic and simply acts as an engine which initiates the communication with the middle end. Although the front end does not do much in terms of the application logic, it is probably the single most important part of the application. A poorly designed and awkward-to-use front end makes all the magic of the middle ware redundant.
In most web applications, the invocation of logic on the middle ware, which may or may not change the information presented to the user, requires that the user click a link or submit data via a form. This in turn requires that the entire page be refreshed and all data be resent to the user. This is OK when a large portion of the page is being refreshed, but it is very wasteful if little or no data is to be updated.

Traditional Web Application

The philosophy behind Ajax is that when a user makes a request to the server-side part of the application, only the data which is required is sent back to the user and rather than reloading the entire page, only the parts which require updating are updated.
Ajax is an acronym for Asynchronous Javascript And XML. It is the use of Javascript code in HTML pages that allows it to make independent requests to the web server. XML is by no means mandatory in an Ajax solution and, in some cases it is completely unnecessary. With Ajax, the front end is split into two parts: the HTML and CSS which deals with the page display and the Ajax engine.

Ajax Application

The Ajax engine is responsible for initiating two way communication with the server in response to user events on the page. It enables developers to enrich and enhance the usability of web applications by creating powerful event driven web front ends, similar to the kind that we are accustomed to on the desktop domain, which respond in almost real time.
You can see a more detailed definition of Ajax and how it fits into the the web design domain, by reading Chapter 1 of the Ajax in Action.
Live E-Mail Validation with AJAX
We are now going to dive into the world of AJAX by creating a simple application which validates and verifies a user’s email address while they are filling out a web form. A prior knowledge of HTML and Javascript is beneficial when following this article, however there is no better way of learning than to manually copy (not copy and paste) and implement the solution yourself.
Normally, email validation and verification is carried out by the server. It often involves a syntax check and the sending of an email containing a link and verification code, which, once clicked, confirms that the email is real and active.
Our small application will do all of this before the form is submitted, or more precisely, while it is being filled out. This kind of feature is especially useful if the form takes several minutes to complete and it can also be extended to include a randomly generated image in place of a plain text code in the verification.
To assist in the creation of our small AJAX application, I have created an Email Validation class, email_validator.php which provides the tools necessary to validate and verify an email address. It uses a SqLite database to store email addresses which are to be verified and provides the necessary methods to check the syntax of the email, validate domain part of the email and sends a randomly generated verification code the email address.
The source code for this class and the documentation can be downloaded in this ZIP file.
Coding for AJAX
It is worth remembering that when introducing or including Ajax in web applications, the coding becomes more complex.
  • Both the Ajax engine and the server side script must understand the context of the request and the response.
  • The order of the requests and responses between the Ajax engine and the server side script (if important), must be known, as there is no guarantee that they will be received in the order that was intended.
  • The server side part of the application must treat any data received from the Ajax engine as “soiled” until it has been validated and verified as correct.
  • The Ajax engine must treat data received from the server as “soiled” until validated and verified.
  • The application should still be fully functional via the regular click and reload mechanism, should Javascript be disabled or unsupported by user’s browser.

The Server-Side PHP

Our Ajax engine’s partner in crime will be a small PHP script called email_validate.php. It receives the data from the Ajax engine, processes it by carrying out the required action and sends a plain text response.

Validating the Data

The data from the Ajax engine will be passed to our script in the URL query string. The three values which are sent are as follows:
  • action – The action must be sent to the script and is used to specify what we want the script to do.
    • validate – to validate the email
    • verify – to verify the verification code
  • id – an ID previously generated by our script and sent to the Ajax engine. We can use this ID to retrieve the email from the SqLite database by passing it to the constructor of the EmailValidator object.
  • email – the email address we wish to verify or validate.
  • v_code – only required when we have an action of verify. The verification code to check against the email address.


PHP:
/* get the action */
$action = @$_GET['action'];

if (isset($_GET['id'])) {
    /* the user has already made a request and been given an email ID */
    
try {
        
$email = new EmailValidator((int)$_GET['id']);
        
        if (isset(
$_GET['email'])) {
       
    /* a new email has been sent, so we must re-validate */
       
    $email->setEmail($_GET['email']);
            
$action = 'validate';
        }
    } catch (
EmailValidatorException $e) {
        if (isset(
$_GET['email'])) {
            
/* the ID was invalid, but we have been sent an email address */
            
$email = new EmailValidator($_GET['email']);
            
$action = 'validate';
        } else {
            
/* an invalid ID was specified and no email address was given - we cannot do much */
            
$action = 'invalid';
        }
    } catch (
Exception $e) {
        
$action = 'unknownerror';
    }
} else if (isset(
$_GET['email'])) {
    try {
        
/* load the new email into the validator */
        
$email = new EmailValidator($_GET['email']);
    } catch (
Exception $e) {
        
$action = 'unknownerror';
    }
} else {
    
/* no action sent – we cannot do much */
    
$action = 'invalid';
}
 

Notice how we have overridden the action variable to re-validate the email address if an email address is sent as well as an ID (indicating that it has changed). We also override the action variable if an error occurs when attempting to create an instance of the EmailValidator object.

1
|
2
|
3
|
4

Download: email_validator.zip