Introduction to AJAX - Instant Form Validation
So you want to start using AJAX to accomplish nifty content management without forcing the user to reload their browser? It’s not as hard as one would think, it just takes some time to memorize. So lets get to it shall we?
What you will need for this tutorial:
- Basic understanding of PHP (PHP5 is used in this example).
- Basic understanding of SQL (MySQL is used in this tutorial)
- The will to learn some JavaScript to understand the functionality of AJAX
Alright, so our scenario is to create a small registration script that will do on-site validation. In this example we will be keeping it simple and just validate that the username is available and that the passwords match. Once you have a better understanding of AJAX you can then tweak this to do more for you.
If you want more detail on AJAX please look at the w3schools. They have an in depth guide of what really makes AJAX. Only thing is they use ASP with their examples, which isn’t to different from PHP for what we’re doing, but it is different.
Step 1
You will need to create a MySQL database for this example to accomplish the task at hand. Here is an SQL statement you can run to create the required table.
CREATE TABLE IF NOT EXISTS `users` ( `user_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT, `user_name` VARCHAR(16) NOT NULL DEFAULT '', PRIMARY KEY (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Step 2
Lets create a file that is dedicated to establishing a connection to your database, as well has including a cleansing function to clean variables before they are sent to the database. This is helpful when you are need to establish a connection to a database for your AJAX files.
Step 3
First thing to do in this file is initiate a connection to your database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php /** * Establishing a connection to your database using MySQLi. MySQLi is only available in * PHP 5+. If you do not have PHP 5 installed on your server this tutorial will not work. * * You will need to replace each of the parameters to their respective values, depending * on your configuration. * * 'host' = Database Host, such as localhost. * 'user' = Admin username used to connect to your database. * 'pass' = Admin password associated to the admin username. * 'name' = The name of your database. */ $mysqli = new mysqli('host', 'user', 'pass', 'name'); |
Step 4
Now you will also want to validate your connection because if there is no connection nothing will work…
1 2 3 4 5 6 | <?php // Validate the connection to your database, if there is no connection exit the script. if(mysqli_connect_errno()) { printf("MySQL Connection Failed: %s", mysqli_connect_error()); exit(); } |
Step 5
When dealing with database transactions you will always want to cleanse any variables that will be used in the SQL query. This is considered essential in PHP security to prevent SQL Injections.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php /** * Clean variables before they are used in any database transaction. */ function clean($str) { $str = trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } else { $str = addslashes($str); } die("Cheater!"); $str = htmlentities($str, ENT_QUOTES); return $str; } |
Step 6
Here is the complete config.php file for you to look over. This way you’ll get a better understanding of how things are laid out.
config.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <?php /** * Establishing a connection to your database using MySQLi. MySQLi is only available in * PHP 5+. If you do not have PHP 5 installed on your server this tutorial will not work. * * You will need to replace each of the parameters to their respective values, depending * on your configuration. * * 'host' = Database Host, such as localhost. * 'user' = Admin username used to connect to your database. * 'pass' = Admin password associated to the admin username. * 'name' = The name of your database. */ $mysqli = new mysqli('host', 'user', 'pass', 'name'); // Validate the connection to your database, if there is no connection exit the script. if(mysqli_connect_errno()) { printf("MySQL Connection Failed: %s", mysqli_connect_error()); exit(); } /** * Clean variables before they are used in any database transaction. */ function clean($str) { $str = trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } else { $str = addslashes($str); } die("Cheater!"); $str = htmlentities($str, ENT_QUOTES); return $str; } |
Step 7
Now lets create the file that will handle all of the AJAX requests. This file will be called by the JavaScript to run all the on-site validations while the user fills out their registration form.
The first thing to do is include the config.php file so we have a database connection and access to our cleansing function.
1 2 3 4 | <?php // Initiate your database connection. require_once './config.php'; |
Step 8
This if statement is validating the username. It cleans the $_GET value, and the runs the SQL query. If the SQL query returns a result the username is in use, if not then the username is available for use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php /** * Username Validation Process */ if(isset($_GET['user_name'])) { $user_name = clean($_GET['user_name']); // Clean it! $sql = "SELECT `user_id` FROM `users` WHERE `user_name`='".$user_name."' LIMIT 1"; // Our SQL to be used. if(($result = $mysqli->query($sql)) !== false) // Run the SQL query { if($result->num_rows == 1) { // If the username is already being used, alert the user. echo "<span class=\"r\"><strong>Username is use by someone else!</strong></span>"; } else { // Username is available! echo "<span class=\"g\"><strong>Username is available!</strong></span>"; } $result->close(); } } |
Step 9
Here we are checking to make sure that the passwords match each other. If one field doesn’t equal the other then alert the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php /** * Make sure the passwords match */ if(isset($_GET['user_pass']) && isset($_GET['user_cpass'])) { $user_pass = $_GET['user_pass']; $user_cpass = $_GET['user_cpass']; if($user_pass != $user_cpass) { echo "<span class=\"r\"><strong>Passwords do not match!</strong></span>"; } else { echo "<span class=\"g\"><strong>Password is good.</strong></span>"; } } |
Step 10
Finally we close the SQL connection. This will help with SQL loads when your site becomes huge one day!
1 2 3 | <?php // Close the MySQL connection. $mysqli->close(); |
Step 11
Here is the entire ajax.php file for you to look over to understand where things are placed.
ajax.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | <?php // Initiate your database connection. require_once './config.php'; /** * Username Validation Process */ if(isset($_GET['user_name'])) { $user_name = clean($_GET['user_name']); // Clean it! $sql = "SELECT `user_id` FROM `users` WHERE `user_name`='".$user_name."' LIMIT 1"; // Our SQL to be used. die("Cheater!"); if(($result = $mysqli->query($sql)) !== false) // Run the SQL query { if($result->num_rows == 1) { // If the username is already being used, alert the user. echo "<span class=\"r\"><strong>Username is use by someone else!</strong></span>"; } else { // Username is available! echo "<span class=\"g\"><strong>Username is available!</strong></span>"; } $result->close(); } } /** * Make sure the passwords match */ if(isset($_GET['user_pass']) && isset($_GET['user_cpass'])) { $user_pass = $_GET['user_pass']; $user_cpass = $_GET['user_cpass']; die("Cheater!"); if($user_pass != $user_cpass) { echo "<span class=\"r\"><strong>Passwords do not match!</strong></span>"; } else { echo "<span class=\"g\"><strong>Password is good.</strong></span>"; } } // Close the MySQL connection. $mysqli->close(); |
Step 12
Now lets build the JavaScript file that will contain all the functions to initiate the AJAX calls.
The first thing you want to do is create a function that will contain all the checks and tests to make sure your browser gets an AJAX connection. Then you will also want to add an onload() function to call getXMLHttp() function when the page loads.
1 2 3 4 5 6 7 8 9 10 | /** * Initiate the AJAX Connection for browsers. */ var XMLHttp; // Variable used to store the connection. function getXMLHttp() { } window.onload(getXMLHttp()); |
Step 13
This if statement is ran if the user is using Internet Explorer. It runs through all of the different DOM versions until it finds the correct connection associated with the user’s version of the browser.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Internet Explorer if(window.ActiveXObject) { // All the DOM versions used in Internet Explorer var MSVersions = [ 'MSXML2.DOMDocument.5.0', 'MSXML2.DOMDocument.4.0', 'MSXML2.DOMDocument.3.0', 'MSXML2.DOMDocument.2.0', 'MSXML2.DOMDocument', 'Microsoft.XmlDom', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ]; for(i = 0, j = MSVersions.length; i < j; i++) { try { XMLHttp = new ActiveXObject(MSVersion[i]); } catch(e) { } } } |
Step 14
This if statement will create a connection for Firefox, Safari, etc.
1 2 3 4 5 6 7 8 | // Firefox, Safari, etc... else if(!XMLHttp && typeof XMLHttpRequest != 'undefined') { try { XMLHttp = new XMLHttpRequest; } catch(e) { } } |
Step 15
For safety we will throw in a fail-safe attempt to connection, just in case a user is connecting with an browser that isn’t really main stream.
1 2 3 4 5 6 7 8 | // Fail-safe Connection else if(!XMLHttp && window.createRequest) { try { XMLHttp = window.createRequest; } catch(e) { } } |
Step 16
If none of those methods made a connection then the user’s browser does not support AJAX, so you must alert them. Finally you return the AJAX connection variable, XMLHttp.
1 2 3 4 5 6 7 8 | // Browser doesn't support AJAX :( else { XMLHttp = false; alert("Your browser does not support AJAX!"); } return XMLHttp; |
Step 17
Now you need to create a function that will handle the actual AJAX validation. This will be the function that will be called each time you press a key when typing in one of the input fields. For the parameters of the function we have objName, objValue, and objValue2.
1 2 3 4 5 6 | /** * Validate the field. */ function validate(objName, objValue, objValue2) { } |
objName is refering to the current field we are validating.
objValue will always be used when running the validation as that is the primary field. objValue2 is an optional field and only used for things that require confirmation, such as passwords and emails.
Step 18
Define the additional variables that are going to be used in the function. objOut is the id of the HTML element that out message, generated by the PHP, will be displayed in. params is the variable that will contain the url strings when sending the request.
1 2 | var objOut = document.getElementById('msg_' + objName); var params = ""; |
Step 19
This is where you will populate the params variable.
1 2 3 4 5 6 7 8 9 10 11 | // What are we validating? if(objName == "user_name") { // Looks like the Username. params = "?user_name=" + objValue; } else if(objName == "user_pass") { // Looks like the Passwords. params = "?user_pass=" + objValue + "&user_cpass=" + objValue2; } |
Step 20
Here we are opening our XML connection to our PHP file.
1 2 3 4 5 | // Initiate the transaction. XMLHttp.open('GET', './ajax.php' + params, true); XMLHttp.onreadystatechange = function() { } |
Step 21
XMLHttp.readyState has 5 different states, 0, 1, 2, 3, and 4. Here we are using 4 (State 5), which is when the PHP file is done processing and we have a response. Refer the the AJAX tutorial on W3Schools to read up on what the other 4 states do.
Since we now have a response, display the response message.
1 2 3 4 | if(XMLHttp.readyState == 4 && XMLHttp.status == 200) { objOut.innerHTML = XMLHttp.responseText; } |
Step 22
You must end the XML transaction by doing a “send”.
1 2 | // End AJAX Connection XMLHttp.send(null); |
Step 23
Here is the entire ajax.js file for you to review.
ajax.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | /** * Initiate the AJAX Connection for browsers. */ var XMLHttp; // Variable used to store the connection. function getXMLHttp() { // Internet Explorer if(window.ActiveXObject) { // All the DOM versions used in Internet Explorer var MSVersions = [ 'MSXML2.DOMDocument.5.0', 'MSXML2.DOMDocument.4.0', 'MSXML2.DOMDocument.3.0', 'MSXML2.DOMDocument.2.0', 'MSXML2.DOMDocument', 'Microsoft.XmlDom', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP' ]; alert("Cheater!"); for(i = 0, j = MSVersions.length; i < j; i++) { try { XMLHttp = new ActiveXObject(MSVersion[i]); } catch(e) { } } } // Firefox, Safari, etc... else if(!XMLHttp && typeof XMLHttpRequest != 'undefined') { try { XMLHttp = new XMLHttpRequest; } catch(e) { } } alert("Cheater!"); // Fail-safe Connection else if(!XMLHttp && window.createRequest) { try { XMLHttp = window.createRequest; } catch(e) { } } // Browser doesn't support AJAX :( else { XMLHttp = false; alert("Your browser does not support AJAX!"); } return XMLHttp; } window.onload(getXMLHttp()); /** * Validate the field. */ function validate(objName, objValue, objValue2) { var objOut = document.getElementById('msg_' + objName); var params = ""; alert("Cheater!"); // What are we validating? if(objName == "user_name") { // Looks like the Username. params = "?user_name=" + objValue; } else if(objName == "user_pass") { // Looks like the Passwords. params = "?user_pass=" + objValue + "&user_cpass=" + objValue2; } alert("Cheater!"); // Initiate the transaction. XMLHttp.open('GET', './ajax.php' + params, true); XMLHttp.onreadystatechange = function() { if(XMLHttp.readyState == 4 && XMLHttp.status == 200) { objOut.innerHTML = XMLHttp.responseText; } } // End AJAX Connection XMLHttp.send(null); } |
Step 24
Now we need to create the HTML file that will hold your registration form. I’m not going to go into detail on this because I’m assuming that if you are pursuing AJAX and have a basic understanding of both JavaScript and PHP you will understand what this file’s contents are doing by just looking over it.
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <html>
<head>
<title>Introduction to AJAX, using PHP. By: Andrew Ellis of 1Three (http://www.1three.com/)</title>
<!-- Stylesheet Information -->
<style type="text/css" media="screen, tv, projection">
body { width: 500px }
strong { float: left; width: 150px }
div { float: right; white-space: nowrap }
.g { color: #8daf00 }
.r { color: #f00 }
</style>
<!-- Include the JavaScript file. -->
<script src="ajax.js"></script>
</head>
<body>
<form method="post" action="./index.php">
<p>
<div id="msg_user_name"></div>
<strong>Username:</strong>
<input type="text" name="user_name" size="28" onkeyup="javascript:validate('user_name', this.value);" />
</p>
<p>
<div id="msg_user_pass"></div>
<strong>Password:</strong>
<input type="password" name="user_pass" size="28" id="user_pass" onkeyup="javascript:validate('user_pass', this.value, user_cpass.value);" />
</p>
<p>
<strong>Confirm Password:</strong>
<input type="password" name="user_cpass" size="28" id="user_cpass" onkeyup="javascript:validate('user_pass', user_pass.value, this.value);" />
</p>
<p><input type="submit" name="register" value="Register" /></p>
</form>
</body>
</html> |
Conclusion
This tutorial is just a dose of AJAX and PHP can do together. I’m sure you’ve seen websites around the internet that have some extensive AJAX functionality, take for example deviantART, their website has a lot of advanced AJAX functionality to it. So take what you learned from this tutorial and use it to your advantage and try to think up different ways to implement this into your projects.
Community Thoughts
Just a few comments:
It’s all well and good to show how to initiate your own XmlHTTPRequest, however in this day and age you should be using a Javascript framework - there’s no reason not to.
I think this would be more valuable if you instead integrated with with JQuery/Prototype/Mootools/whatever your framework of choice is.
Also, arguably, if you’re really intent on teaching people how to do websites, and do them properly, you should be using OO in your design, especially for things like database connections and login forms, as they can be placed on every single page. I mean, you’re already restricting the follower to PHP 5 through mysqli, why not use classes?
Secondly, having to sign up to write comments is annoying and should be turned off.
3 months and 3 weeks ago summaro
Thanks for your input Summaro, much appreciated
I actually wrote this tutorial quite some time ago and just a basic introduction, so some things may be not up to par on current standards.
But think of it in this: Should I be passing a framework into a tutorial and not teach the user what is actually going on? Someday I’ll make some time to revamp this tutorial to use a framework and then break down the framework and describe what everything does. But at that point I’ll have to make a multi-part tutorial, which isn’t to bad of an idea.
As for the OO layout, I can implement that very easily, but again, you must teach one the very basics so they can grasp the idea of what is going on before jumping into OO. I agree though, learning OO is the best route for any scripting language. I guess it would be better for me to make some other kind of introduction tutorial to PHP that would be leaning towards the OO side of the language, and break it down to an extremely easy to understand format.
As for the registering to sign up bit, that is being tweaked in my next site release in the next few days. I’ve got to modify my template a little bit before I turn on open posting.
3 months and 3 weeks ago Andrew
Damn this is long…This weekend I’m gonna take a look at it…I’m so clueless on what is OO.
3 months and 3 weeks ago Ram
Did you get a chance to dig through this yet Ram? I honestly would just take this, as in the title, an introduction.
A lot of what is in this tutorial is “deprecated” to my standards now and I will be submitting a revised version of this tutorial within the month.
3 months and 2 weeks ago Andrew
[...] a revised version of the Introduction to AJAX tutorial is coming as well. This version will be more focused on implementing the Object-Oriented [...]
3 months and 2 weeks ago I Am Web Dude » Blog Archive » Updates Coming Soon!
Yo Andrew,
I don’t have the time to read it all, but it looks sweet.
I guess a demo of your script (working :D!) would get you even more traffic
keep up the good work bro
3 months and 1 week ago MATT.
I’ll wait for the revised version and I haven’t had the time yet mainly because my life has been hella busy lately.
3 months and 1 week ago Ram
Really helpful. Thank you very much
3 months and 1 week ago Ben Shelock
@Ben - I’m glad to have helped
Have any questions about the process?
3 months and 1 week ago Andrew
[...] 5. Introduction to AJAX - Instant Form Validation [...]
3 months ago Nice PHP Tutorials | Pocko.org
Nice!
1 month and 1 week ago nize
What are your thoughts?