Escolar Documentos
Profissional Documentos
Cultura Documentos
Ajax is a catchy name for a type of programming made popular in 2005 by Google and other big web developers. Ajax loosely stands
for AsynchronousJavascript And XML, but that just sounds like techno jargon to many people.
Advertise on Tizag.com
In plain English, Ajax can be thought of Javascript on steroids.
<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
This lesson will show you how to create the keystone of Ajax; the XMLHttpRequest object. Not only will you know how to make this important
Ajax object, but you will also know how to make it compatible with all the popular browsers: Internet Explorer, Opera, Firefox, and Safari.
ajax - try/catch blocks of code
To create this important Ajax object, you are going to have to use a special programming technique known as "try and catch". Basically it
attempts to "try" a piece of code and if that piece causes an error it "catches" the error and keeps going. Normally when an error occurs the code
will stop running, however, the "catch" eats up the error and lets the code continue.
In the following code we are going to "try" three different ways to make a new XMLHttpRequest object. Every time we fail and get an error, we
will catch the error and try the next a different command.
Note: If our "try" is successful then the "catch" code will not be run because it is only used when there is an error.
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
In the above Javascript code, we try three times to make our XMLHttpRequest object. Our first attempt:
• ajaxRequest = new XMLHttpRequest();
is for the Opera 8.0+, Firefox and Safari browsers. If that fails we try two more times to make the correct object for an Internet Explorer
browser with:
• ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
• ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");>
If that doesn't work, then they are using a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support
Ajax.
Most likely though, our variable ajaxRequest will now be set to whateverXMLHttpRequest standard the browser uses and we can start sending
data to the server.
Javascript Code:
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
// We still need to write some code here
}
This property, onreadystatechange, stores a function. As the name sort of implies, every time the "ready state" changes this function will be
executed. What is this "ready state" and is it any use to us?
Javascript Code:
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
// Get the data from the server's response
}
}
Now that we know how to check if the response is complete, we can access the property that stores the server's response, responseText.
Javascript Code:
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
Phew! That was a lot of new things we had to use to get our server's response, but now we can rest easy knowing we are ready to send off a
request to the server. Using Ajax, we can now ask our server for some data!
Javascript Code:
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "serverTime.php", true);
With all of our Javascript setup work complete, we can then use the sendmethod to send our request to the server.
Javascript Code:
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);
Javascript Code:
<input type='text' onChange="ajaxFunction();" name='username' /> <br />
OK, now we are ready to completely update our "order.html" file to be 100% Ajax ready.
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
Display of order.html:
Top of Form
Name:
Time:
Bottom of Form
Sweet! The time text box pulled down the server's time from "serverTime.php" without having to reload the entire page! Congratulations you've
just written your first fully-functional Ajax application!
update order.html
We want to be able to build queries from our HTML file, so there are a few form elements that will need to be added. The three inputs we are
going to implement are:
• Maximum Age (Text Input) - Let the user select the maximum age to be returned.
• Maximum WPM (Text Input) - Let the user select the maximum wpm to returned.
• Gender (Select Input) - Let the user select the gender of a valid person.
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option>m</option>
<option>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
</body>
</html>
If the new Javascript code is foreign to you, be sure to check out our lesson on Javascript's getElementById Function.
With our new Javascript code
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
we have built a query string to pass along the information from our HTML form to our PHP script.
ajax-example.php Code:
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
$query .= " AND ae_age <= $age";
if(is_numeric($wpm))
$query .= " AND ae_wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value='m'>m</option>
<option value='f'>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Display:
Top of Form
Max Age:
Max WPM:
Sex:
Bottom of Form
Your result will display here