27.10.2015 Views

AJAX and PHP

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4<br />

}<br />

}<br />

?><br />

return ($value == 'true' || $value == 'on') ? 1 : 0;<br />

13. Test your script by loading http://localhost/ajax/validate/index.php in a<br />

web browser.<br />

What Just Happened?<br />

The <strong>AJAX</strong> validation technique allows us to validate form fields <strong>and</strong> at the same time inform<br />

users if there were any validation errors. But the cherry on the top of the cake is that we are doing<br />

all of this without interrupting the user's activity! This is called unobtrusive form validation.<br />

The unobtrusive validation is combined with a pure server-side <strong>PHP</strong> validation that happens when<br />

submitting the form. At the server, both validation types are supported by a <strong>PHP</strong> script called<br />

validate.php, with the help of another <strong>PHP</strong> script called validate.class.php.<br />

Let us examine the code, starting with the script that h<strong>and</strong>les client-side validation, index.php. In<br />

this validation example, the client page is not a simple HTML file, but a <strong>PHP</strong> file instead, so portions<br />

of it will be still dynamically generated at the server side. This is necessary because we want to<br />

retain the form field values when the form is submitted <strong>and</strong> server-side validation fails. Without<br />

the help of the <strong>PHP</strong> code, when the index page is reloaded, all its fields would become empty.<br />

index.php starts with loading a helper script named index_top.php, which starts the session by<br />

calling session_start(), defines some variables <strong>and</strong> a function that will be used later in index.php,<br />

<strong>and</strong> initializes some session variables ($_SESSION['values'] <strong>and</strong> $_SESSION['errors']) that we<br />

will be using to avoid <strong>PHP</strong> sending notices about variables that are not initialized.<br />

Notice the onload event of the body tag in index.php. It calls the setFocus() function defined in<br />

validate.js, which sets the input cursor on the first form field.<br />

Later in index.php, you will see the following sequence of code repeating itself, with only<br />

small changes:<br />

<br />

Desired username:<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!