July 17th, 2008
Tutorial : Intoduction to AJAX with PHP
Ajax Application using PHP/MySQL
Lets create a Username Validator Application using AJAX/PHP i.e Takes a username input, checks with the database/array to see whether the username is available or not and returns the result. You can extend it by using a database as well, but right now, I am trying to keep it as simple as possible. To achieve this, we need to create 2 pages
- usernamechecker.html
- check.php
You can see the demo here.
Before we begin, you need to have php installed in your system (Although PHP is not compulsary for AJAX to work), if you don`t know how to do that, You can read Tutorial : Installing Apache, PHP 5, MySQL 5 & PhpMyAdmin 2.11 in Windows Vista/XP to install PHP/mySQL etc on your local machine to set up a developer’s environment.
STEP 1 : Our Basic HTML page
If you have seen the demo page, you will notice that it only has one text field. It takes the username as input.
The code of the HTML page is given below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Username checker</title>
<style>
.green { color:#0F0; }
.red { color:#F00; }
</style>
</head>
<body>
<input name="username" id="username" type="text"/>
<div id="result"><!-- Stores the result !--></div>
</body>
</html>
Note that we have written CSS styling to the page as well.
STEP 2 : Writing the Javascript
Ok ! After creating our basic HTML page, lets code the javascript for it. Remember it is a dynamic page, so the result will be displayed without the need of reloading the page.DIV with id=”result” is the container which will display our result.
<script type="text/javascript">
//Checking whether browser is the latest version of IE
try {
//If yes, create object of XMLHttpRequest
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
alert("You are using the latest IE browser");
} catch(e) {
//IF not latest browser
//Checking if browser is a old version of IE
try {
//If yes, create object of XMLHttpRequest
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert("You are using an old version of IE browser");
} catch(e) {
//If not both, then it is a NON-IE Browser
xmlhttp=false;
}
}
//Checking if browser is a non IE browser
if(!xmlhttp && typeof XMLHttpRequest != 'undefined') {
//Creating an object of XMLHttpRequest in non-IE browsers
xmlhttp = new XMLHttpRequest();
alert("You are using non IE Browser");
}
function check() {
var obj = document.getElementById('result');
var userfield = document.getElementById('username');
xmlhttp.open("GET", 'check.php?username='+userfield.value); //Opens connection to the scriptpage using GET response method
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText == 'Username taken') {
obj.className = "red";
obj.innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.responseText == 'Username available') {
obj.className = "green";
obj.innerHTML = xmlhttp.responseText;
}
}
else {
obj.innerHTML = '<span style="color:#000";">Loading...</span>';
}
}
xmlhttp.send(null);
}
</script>
The code is very similar to what we had written in the previous page. The new line here is obj.className = “”. It gives us the power to add CSS styling to the result div. So using the above code, if username is not available, the text will be displayed in RED while if username is available then the text will be displayed in GREEN !
STEP 3 : Adding the PHP File
This is the script which takes the input from the textfield, checks it with a simple if condition and then accordingly prints the text. This text is returned to the javascript function we had written.
<?php if($_GET['username'] == 'abc' || $_GET['username']=='xyz') echo "Username taken"; else echo "Username available"; ?>
Thats it ! Now finally there is one more thing we have to do, integrate the javascript in to the HTML page, and then write a call in the textfield.
STEP 4 : Adding Call to HTML page
We have to tell the textfield to execute the javascript check() function. We can do this by adding one of the form properties to the input textfield.
<input name="username" id="username" type="text" onKeyPress="check();" />
We are telling the browser that on every key press, it must execute the function check(). This way, our function can return the value to the check.php script and get the results back.
Voila ! Now just integrate the javascript inside the part of the HTML page.
STEP 5 : Integration
Your final usernamechecker.html should look something like this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Username checker</title>
<style>
.green { color:#0F0; }
.red { color:#F00; }
</style>
<script type="text/javascript">
//Checking whether browser is the latest version of IE
try {
//If yes, create object of XMLHttpRequest
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
alert("You are using the latest IE browser");
} catch(e) {
//IF not latest browser
//Checking if browser is a old version of IE
try {
//If yes, create object of XMLHttpRequest
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert("You are using an old version of IE browser");
} catch(e) {
//If not both, then it is a NON-IE Browser
xmlhttp=false;
}
}
//Checking if browser is a non IE browser
if(!xmlhttp && typeof XMLHttpRequest != 'undefined') {
//Creating an object of XMLHttpRequest in non-IE browsers
xmlhttp = new XMLHttpRequest();
alert("You are using non IE Browser");
}
function check() {
var obj = document.getElementById('result');
var userfield = document.getElementById('username');
xmlhttp.open("GET", 'check.php?username='+userfield.value); //Opens connection to the scriptpage using GET response method
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText == 'Username taken') {
obj.className = "red";
obj.innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.responseText == 'Username available') {
obj.className = "green";
obj.innerHTML = xmlhttp.responseText;
}
}
else {
obj.innerHTML = '<span style="color:#000";">Loading...</span>';
}
}
xmlhttp.send(null);
}
</script>
</head>
<body>
<input name="username" id="username" type="text" onKeyPress="check();" />
<div id="result">
</div>
</body>
</html>
STEP 6 : Testing
Like I said, you need to have PHP installed. If you have followed my tutorial in installing PHP/mySQL etc, then put the usernamechecker.html and check.php inside the public_html folder, then point your browser to www.myserver.dev/usernamechecker.html
Well thats about it. This was a very basic AJAX tutorial, If you need any help, you can always email me or post comments here.
Watch out this space for more advanced tutorials in AJAX.
Cya















November 13, 2008 at 3:39 am
you should change the onkeypress in the input tage to onkeyup so it validates after every character not before a new character is pressed. this way you don’t have to press enter after you have entered a name.
November 4, 2008 at 6:51 pm
I tried exactly the things mentioned in this tutorial.After typing in the words in the input field ,it seems to do nothing as if it can’t load check.php to get response and hence only shows ‘loading…’.Both the html , php file are in the same folder.Can you think of any mistake i might be doing?
October 7, 2008 at 8:19 pm
For some reason I cannot see the AJAX code when I click on the link
September 17, 2008 at 5:34 pm
Very nice, simple example. Thank you!
September 11, 2008 at 12:51 pm
I want to get the source code PHP with AJAX.