This is the PHP and AJAX form validation application you create in Chapter 4 of AJAX and PHP: Building Responsive Web Applications.
This degradable form validation demo verifies the form at the server side on the classic form submit, and also implements AJAX validation while the user navigates through the form. The final validation is performed at the server, as shown in the following diagram.
Doing a final server-side validation when the form is submitted is always a must. If someone disables JavaScript in the browser settings, AJAX validation on the client side won't work, exposing sensitive data, and thereby allowing an evil-intended visitor to harm important data back on the server (for example, through SQL injection). Always validate user input on the server!
This form validation application validates a registration form, using both AJAX validation (client side) and typical server-side validation:
Both AJAX validation and PHP validation check the entered data against these rules:
A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. In this exercise, we need to make an asynchronous request to the server to validate the entered data every time the user leaves an input box or changes a selection.
The hidden danger behind this technique is only revealed if the user moves very quickly through the input fields, or the server connection is slow; in these cases, the web application would attempt to make new server requests through an XMLHttpRequest object that is still busy waiting for the response to a previous request (this would generate an error and the application would stop functioning properly).
Depending on the circumstances at hand, the ideal solution to this problem may be:
In this form validation exercise, we use a message queue. When the user leaves an input element, a message to validate its value is added to the queue. When the XMLHttpRequest object is clear to make a new request, it takes the first message from the queue.
The queue is a First-In, First-Out (FIFO) structure, which guarantees that the messages are sent in the proper order. To get a feeling about how this works, go to the demo page for this chapter (or implement the code), and press tab quickly multiple times, and then wait to see how the validation responses show up one by one.
Note that dealing with these problems only makes sense in scenarios where elements outside your control can trigger the server requests. Otherwise, in scenarios such as the Friendly application from Chapter 3, where you initiated new requests only after the response was received, implementing thread-safe code doesn't make a huge difference.
The complete AJAX and PHP tutorial features even more AJAX web development examples.
PHP developer? Learn PHP SEO (Search Engine Optimization) techniques. (ASP.NET SEO tutorial forthcoming)