You are on page 1of 14

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

1 de 14 02/06/2006 16:10
Tutorial bsico del mtodo AJAX con PHP y MySQL
The XMLHttpRequest object is a handy dandy JavaScript object that offers a convenient way for webpages to get information from
servers without refreshing themselves.
The benefit to end users is that they don't have to type as much and they don't have to wait as long. For example, having the
user's city and state show up in a webpage automatically after the ZIP code has been typed in is a big time saver.
Although the XMLHttpRequest object might sound complex and different from any other JavaScript object you have ever used, it
really isn't. A good way to think of the XMLHttpRequest object is as you would think of the JavaScript Image object. As we know,
with the Image object you can dynamically specify a new URL for the image source without reloading the page. Similarly with the
XMLHttpRequest object, you can dynamically specify a URL to get some server data without reloading the page.
The purpose of this article is to demonstrate through a series of baby steps just how easy it is to use the XMLHttpRequest object.
In order to complete this tutorial you should have some basic PHP, MySQL and JavaScript experience. That said, the PHP
programming in these examples is so basic that if you do not have PHP experience, it may still be possible for you to look at the
PHP code and apply the functionality to your weapon of choice, be it PERL, ASP, or JSP.
Creating the Form
We first create a simple webpage that has the HTML for our Web form. There is nothing out of the ordinary here - just basic
HTML defining the city, state, and ZIP code.
PHP [inicio]
PHP [fin]
1.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 1.
< 2.
html xmlns="http://www.w3.org/1999/xhtml" >
< 3.
head>
< 4.
title>ZIP Code to City and State using XmlHttpRequest</title>
</ 5.
head>
< 6.
body>
< 7.
form action="post">
< 8.
p>
9.
ZIP code:
< 10.
input type="text" size="5" name="zip" id="zip" />
</ 11.
p>
12.
City:
< 13.
input type="text" name="city" id="city" />
14.
State:
< 15.
input type="text" size="2" name="state" id="state" />
</ 16.
form>
</ 17.
body>
</ 18.
html>
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
2 de 14 02/06/2006 16:10
Adding the Event Handler
We then add an onblur event handler function named updateCityState(). This event handler is called whenever the ZIP code
field loses focus.
onblur="updateCityState();"
The updateCityState() function will be in charge of asking the server what the city and state is for a given Zip code. For
now, this function does nothing. We will add its guts later.
PHP [inicio]
PHP [fin]
2.
Creating the XMLHttpRequest Object
Of course we need to create an XMLHttpRequest object. Because of variations among the Web browsers, creating this
object is more complicated than it need be. The best way to create the XMLHttpRequest object is to use a function named
getHTTPObject(). This function has precompile directives which make it pretty cross-browser compatible. Don't worry if the
code inside the function is unclear to you. It's not important that you understand its inner workings.
PHP [inicio]
3.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 1.
< 2.
html xmlns="http://www.w3.org/1999/xhtml" >
< 3.
head>
< 4.
title>ZIP Code to City and State using XmlHttpRequest</title>
< 5.
script language="javascript" type="text/javascript"> function updateCityState() { } </script>
6.
</head>
<body> 7.
<form action="post"> 8.
<p> 9.
ZIP code: 10.
<input 11.
type="text" size="5" name="zip" id="zip" 12.
onblur="updateCityState();" 13.
/> 14.
</p> 15.
City: 16.
<input type="text" name="city" id="city" /> 17.
State: 18.
<input type="text" size="2" name="state" id="state" /> 19.
</form> 20.
</body> 21.
</html> 22.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
3 de 14 02/06/2006 16:10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 1.
< 2.
html xmlns="http://www.w3.org/1999/xhtml" >
< 3.
head>
< 4.
title>ZIP Code to City and State using XmlHttpRequest</title>
< 5.
script language="javascript" type="text/javascript">
function 6.
updateCityState() {
} 7.
function 8.
getHTTPObject() {
var 9.
xmlhttp;
10.
/*@cc_on
@if (@_jscript_version >= 5) 11.
try 12.
{ 13.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 14.
} 15.
catch (e) 16.
{ 17.
try 18.
{ 19.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 20.
} 21.
catch (E) 22.
{ 23.
xmlhttp = false; 24.
} 25.
} 26.
@else xmlhttp = false; 27.
@end @*/ 28.
29.
30.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{ 31.
32.
try
33.
{
34.
xmlhttp = new XMLHttpRequest();
} 35.
36.
catch (e)
{ 37.
38.
xmlhttp = false;
} 39.
} 40.
return 41.
xmlhttp;
} 42.
var 43.
http = getHTTPObject(); // We create the HTTP Object
44.
</script>
45.
</head>
<body> 46.
<form action="post"> 47.
<p> 48.
ZIP code: 49.
<input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" /> 50.
</p> 51.
City: 52.
<input type="text" name="city" id="city" /> 53.
State: 54.
<input type="text" size="2" name="state" id="state" /> 55.
</form> 56.
</body> 57.
</html> 58.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
4 de 14 02/06/2006 16:10
PHP [fin]
Some Instant Gratification
Now lets get some instant gratification and add the code that makes the round trip to the server. We first specify the URL
for the server-side script to be getCityState.php?param= . This URL will then have the ZIP Code appended to it so that the
ZIP code is passed as an HTTP GET parameter named param. This means that if a user types in the ZIP code of 17534, the
resulting URL would be getCityState.php?param=17534.
Before we send the HTTP request, we specify the onreadystatechange property to be the name of our new function
handleHttpResponse(). This means that every time the HTTP ready state has changed, our function handleHttpResponse()
is called.
Our new function handleHttpResponse() sits there waiting to be called and when it does get called, it check to see if the
readState is equal to 4. If it is equal to 4 this means that the request is complete. Since the request is complete, it is now
fair game to grab the response text (responseText), unpack it, and set the city and state form fields to the returned values.
(More readyState info found here.)
PHP [inicio]
4.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
5 de 14 02/06/2006 16:10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 1.
< 2.
html xmlns="http://www.w3.org/1999/xhtml" >
< 3.
head>
< 4.
title>ZIP Code to City and State using XmlHttpRequest</title>
< 5.
script language="javascript" type="text/javascript">
var 6.
url = "getCityState.php?param="; // The server-side script function handleHttpResponse() { if (http.readyState == 4) { // Split the comma delimited response into an array results = http.responseText.split(","); document.getElementById('city').value = results[0]; document.getElementById('state').value = results[1]; } }
7.
function updateCityState() {
var 8.
zipValue = document.getElementById("zip").value; http.open("GET", url + escape(zipValue),
9.
} 10.
function 11.
getHTTPObject() {
var 12.
xmlhttp;
13.
/*@cc_on
@if (@_jscript_version >= 5) 14.
try { 15.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 16.
} catch (e) { 17.
try { 18.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 19.
} catch (E) { 20.
xmlhttp = false; 21.
} 22.
} 23.
@else 24.
xmlhttp = false; 25.
@end @*/ 26.
27.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
28.
try {
29.
xmlhttp = new XMLHttpRequest();
} 30.
catch (e) {
31.
xmlhttp = false;
} 32.
} 33.
return 34.
xmlhttp;
} 35.
var 36.
http = getHTTPObject(); // We create the HTTP Object
37.
</script>
38.
</head>
<body> 39.
<form action="post"> 40.
<p> 41.
ZIP code: 42.
<input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" /> 43.
</p> 44.
City: 45.
<input type="text" name="city" id="city" /> 46.
State: 47.
<input type="text" size="2" name="state" id="state" /> 48.
</form> 49.
</body> 50.
</html> 51.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
6 de 14 02/06/2006 16:10
PHP [fin]
I promised instant gratification so lets now create a PHP file named getCityState.php. All this file does is return "Buzzard
Puckey,NM" as the city and state. This means that anytime the focus leaves the ZIP code field, the city and state will be
automatically set to Buzzard Puckey, NM.
PHP [inicio]
PHP [fin]
Creating the ZIP code database
This tutorial refers to a MySQL table named zipcodes. The easiest way to create the zipcodes table in our MySQL database
is to execute a prepackaged SQL query. If you have PhpMyAdmin installed, you can simply navigate to your database of
choice and then eqecute the SQL query below. A zipcodes table will created in your database.
SQL [inicio]
SQL [fin]
The data for our ZIP code database is in a Comma Separated Value (CSV) file format. The best way to add the data in this
file to our table is to run PhpMyAdmin and perform the following steps.
Select the zipcodes table in PhpMyAdmin to bring up its corresponding page. 1.
Scroll to the bottom of the zipcodes table page and look for a link that says "Insert data from a textfile into table". 2.
Click on the "Insert data from a textfile into table" link . 3.
Complete the properties for the text file. It's fields are terminated by ',' and the LOAD method should be "DATA
LOCAL". Once filled out, the form should look similar to the image below:
4.
PhpMyAdmin Graphic Click the "Submit" button 5.
5.
Querying the ZIP Code Database
We will retrieve the matching city and state from our zipcodes table by performing a simple query. Using the code below,
modify lines 9-11 to reflect your database settings and then save the file as getCityState.php
Once you have changed the code to reflect your database settings, a good way to test this file is to use your Web browser
and launch its URL complete with a query string containing a ZIP code. An example of what the URL would look like is the
following:
http://localhost/step6/getCityState.php?param=17534
Did the above URL produce a city,state pair as output? If so you are good to go.
Try out the ZIP code functionality with the HTML file you created containing the XMLHttpRequest code.
PHP [inicio]
6.
<?php 1.
2.
echo "Buzzard Puckey,NM";
3.
?>
# 1.
# TABLE structure FOR TABLE `zipcodes` 2.
# 3.
4. CREATE TABLE `zipcodes` ( 5.
`zipcode` mediumINT(9) NOT NULL DEFAULT '0', 6.
`city` TINYTEXT NOT NULL, 7.
`state` char(2) NOT NULL DEFAULT '', 8.
`areacode` smallINT(6) NOT NULL DEFAULT '0', 9.
PRIMARY KEY (`zipcode`), 10.
UNIQUE KEY `zipcode_2` (`zipcode`), 11.
KEY `zipcode` (`zipcode`) 12.
) TYPE=MyISAM; 13.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
7 de 14 02/06/2006 16:10
<?php 1.
2.
/**
* Connects to the database. 3.
* Return false if connection failed. 4.
* Be sure to change the $database_name. $database_username , and 5.
* $database_password values to reflect your database settings. 6.
*/ 7.
8.
function db_connect() {
9.
$database_name =
10.
'mysql'
11.
; // Set this to your Database Name
12.
$database_username =
13.
'root'
14.
; // Set this to your MySQL username
15.
$database_password =
16.
''
17.
; // Set this to your MySQL password
18.
$result = mysql_pconnect('localhost',$database_username, $database_password);
if (! 19.
$result) return false;
if (! 20.
mysql_select_db($database_name)) return false;
return 21.
$result;
} 22.
23.
$conn = db_connect(); // Connect to database
24.
if ($conn) {
25.
$zipcode = $_GET['param']; // The parameter passed to us
26.
$query = "select * from zipcodes where zipcode = '$zipcode'" ;
27.
$result = mysql_query($query,$conn);
28.
$count = mysql_num_rows($result);
if ( 29.
$count > 0) {
30.
$city = mysql_result($result,0,'city');
31.
$state = mysql_result($result,0,'state');
} 32.
} 33.
if (isset( 34.
$city) && isset($state)) {
35.
$return_value = $city . "," . $state;
} 36.
else { 37.
38.
$return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes
39.
}
echo 40.
$return_value; // This will become the response value for the XMLHttpRequest object
41.
?>
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
8 de 14 02/06/2006 16:10
PHP [fin]
Room for Improvement
In our haste to get our code up and running, we have neglected the following scenarios:
Invalid ZIP codes are typed in. 1.
The visitor's browser does not support the XMLHttpRequest object. 2.
A request is made before the last request has completed. 3.
Lets make ourselves feel all warm and fuzzy inside and add the highlighted code below to our HTML file:
PHP [inicio]
7.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
9 de 14 02/06/2006 16:10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 1.
< 2.
html xmlns="http://www.w3.org/1999/xhtml" >
< 3.
head>
< 4.
title>ZIP Code to City and State using XmlHttpRequest</title>
< 5.
script language="javascript" type="text/javascript">
var 6.
url = "getCityState.php?param="; // The server-side script
7.
function handleHttpResponse() {
if ( 8.
http.readyState == 4) {
9.
if ( 10.
http.responseText.indexOf('invalid') == -1) {
11.
12.
// Split the comma delimited response into an array
13.
results = http.responseText.split(",");
14.
document.getElementById('city').value = results[0];
15.
document.getElementById('state').value = results[1];
16.
17.
isWorking = false;
18.
19.
} 20.
21.
} 22.
} 23.
var 24.
isWorking = false;
25.
function 26.
updateCityState() {
27.
if (! 28.
isWorking && http) {
29.
var 30.
zipValue = document.getElementById("zip").value;
31.
http.open("GET", url + escape(zipValue), true);
32.
http.onreadystatechange = handleHttpResponse;
33.
34.
isWorking = true;
35.
36.
http.send(null);
37.
} 38.
39.
} 40.
function 41.
getHTTPObject() {
var 42.
xmlhttp;
43.
/*@cc_on
@if (@_jscript_version >= 5) 44.
try { 45.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 46.
} catch (e) { 47.
try { 48.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 49.
} catch (E) { 50.
xmlhttp = false; 51.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
10 de 14 02/06/2006 16:10
PHP [fin]
What about the XML?
Ok, by now you might be asking yourself, "what about with the XML"? After all, we are using the JavaScript
XMLHttpRequest object - not the PlainTextHttpRequest object. Are you feeling jipped?
Let me explain. For our ZIP code example, since the query return results are so simple, there hasn't really been a need to
use XML. That said, we all would like to do a little XML, if only for the sake of fluffing our resume's with more XML
experience. Lets convert the query return results to XML. This is done on the server side by editing getCityState.php .
We first comment out line #29 which was the old way of packaging the city and state data. 1.
Next we add line #30 which packages the city and state in XML. There are more elegant ways to do this, but for
now quick and dirty will work.
2.
Finally, we add line #36 which generates the necessary XML header:
header('Content-Type: text/xml');
Without this header, the JavaScript XMLHttpRequest object will not recognize the data as XML, and you will find
yourself beating your head against the wall for quite some time.
PHP [inicio]
3.
8.
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
11 de 14 02/06/2006 16:10
PHP [fin]
On the client side, we switch to using the responseXML property rather than the responseText property for retrieving the
output from our server script. The responseXML property gives us an XMLDocument object that we can traverse to get our
city and state data.
<?php 1.
2.
/**
* Connects to the database. 3.
* Return false if connection failed. 4.
* Be sure to change the $database_name. $database_username , and 5.
* $database_password values to reflect your database settings. 6.
*/ 7.
8.
function db_connect() {
9.
$database_name = 'mysql'; // Set this to your Database Name
10.
$database_username = 'root'; // Set this to your MySQL username
11.
$database_password = ''; // Set this to your MySQL password
12.
$result = mysql_pconnect('localhost',$database_username, $database_password);
if (! 13.
$result) return false;
if (! 14.
mysql_select_db($database_name)) return false;
return 15.
$result;
} 16.
17.
$conn = db_connect(); // Connect to database
18.
if ($conn) {
19.
$zipcode = $_GET['param']; // The parameter passed to us
20.
$query = "select * from zipcodes where zipcode = '$zipcode'" ;
21.
$result = mysql_query($query,$conn);
22.
$count = mysql_num_rows($result);
if ( 23.
$count > 0) {
24.
$city = mysql_result($result,0,'city');
25.
$state = mysql_result($result,0,'state');
} 26.
} 27.
if (isset( 28.
$city) && isset($state)) {
29.
// $return_value = $city . "," . $state;
30.
$return_value = '<?xml version="1.0" standalone="yes"?><zip><city>' .$city.'</city><state>'
31.
} 32.
else { 33.
34.
$return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes
35.
}
36.
header('Content-Type: text/xml');
37.
echo 38.
$return_value; // This will become the response value for the XMLHttpRequest object
39.
?>
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
12 de 14 02/06/2006 16:10
PHP [inicio]
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
13 de 14 02/06/2006 16:10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 1.
< 2.
html xmlns="http://www.w3.org/1999/xhtml" >
< 3.
head>
< 4.
title>ZIP Code to City and State using XmlHttpRequest</title>
< 5.
script language="javascript" type="text/javascript">
var 6.
url = "getCityState.php?param="; // The server-side script
7.
function handleHttpResponse() {
if ( 8.
http.readyState == 4) {
if ( 9.
http.responseText.indexOf('invalid') == -1) {
10.
// Use the XML DOM to unpack the city and state data var xmlDocument = http.responseXML; var city = xmlDocument.getElementsByTagName('city').item(0).firstChild.data; var state = xmlDocument.getElementsByTagName('state').item(0).firstChild.data;
11.
12.
document.getElementById('city').value = city;
13.
document.getElementById('state').value = state;
14.
isWorking = false;
} 15.
} 16.
} 17.
var 18.
isWorking = false;
function 19.
updateCityState() {
if (! 20.
isWorking && http) {
var 21.
zipValue = document.getElementById("zip").value;
22.
http.open("GET", url + escape(zipValue), true);
23.
http.onreadystatechange = handleHttpResponse;
24.
isWorking = true;
25.
http.send(null);
} 26.
} 27.
function 28.
getHTTPObject() {
var 29.
xmlhttp;
30.
/*@cc_on
@if (@_jscript_version >= 5) 31.
try { 32.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 33.
} catch (e) { 34.
try { 35.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 36.
} catch (E) { 37.
xmlhttp = false; 38.
} 39.
} 40.
@else 41.
xmlhttp = false; 42.
@end @*/ 43.
44.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
45.
try {
46.
xmlhttp = new XMLHttpRequest();
47.
xmlhttp.overrideMimeType("text/xml");
} 48.
catch (e) {
Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con... file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...
14 de 14 02/06/2006 16:10
PHP [fin]
Final Thoughts
Using the XMLHttpRequest object to perform remote scripting is a pretty straight forward process. Although XML data can
be retrieved pretty easily with the XMLHttpRequest object, it is not a requirement for you to use XML as your data format.
For simple data such as in our ZIP code example, it actually makes more sense to not use XML. XML has downsides. One
downside is that XML necessitates validation which has a performance impact. In addition, the XML representation of our
data required much more bandwidth to transfer than the non-XML data.
The ZIP code data file that was provided could be out of date. Unfortunately, to use the latest data means that you will
need to subscribe to a service. The USPS offers a Web service however it looks like you need to either agree to use their
service for shipping exclusively with USPS or you need to pay them a large chunk of money. There are many companies that
provide ZIP code data services that you can find easily on Google.
With the ZIP code example, we did not fool with the area code. Adding automatic completion of the area code is dirt easy to
do. I just chose not to include it for the sake of making the example as concise as possible.
9.
Articulos similares:
Using the XML HTTP Request object
El objeto XMLHttpRequest
AJAX un nuevo acercamiento a Aplicaciones Web
Remote Scripting
RPC va HTTP o Como recoger informacin desde el servidor sin recargar la pgina.
Recarga de pgina controlada
Tutorial de AJAX (Asynchronous JavaScript + XML)

You might also like