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...

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.

1. 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]

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.d 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>
PHP [fin]

1 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

2. 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]

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.d 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> 7. <body> 8. <form action="post"> 9. <p> 10. ZIP code: 11. <input 12. type="text" size="5" name="zip" id="zip" 13. onblur="updateCityState();" 14. /> 15. </p> 16. City: 17. <input type="text" name="city" id="city" /> 18. State: 19. <input type="text" size="2" name="state" id="state" /> 20. </form> 21. </body> 22. </html>
PHP [fin] 3. 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]

2 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

3 de 14

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.d 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"> 6. function updateCityState() { 7. } 8. function getHTTPObject() { 9. var xmlhttp; 10. /*@cc_on 11. @if (@_jscript_version >= 5) 12. try 13. { 14. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 15. } 16. catch (e) 17. { 18. try 19. { 20. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 21. } 22. catch (E) 23. { 24. xmlhttp = false; 25. } 26. } 27. @else xmlhttp = false; 28. @end @*/ 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. } 41. return xmlhttp; 42. } 43. var http = getHTTPObject(); // We create the HTTP Object 44. </script> 45. </head> 46. <body> 47. <form action="post"> 48. <p> 49. ZIP code: 50. <input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" /> 51. </p> 52. City: 53. <input type="text" name="city" id="city" /> 54. State: 55. <input type="text" size="2" name="state" id="state" /> 56. </form> 57. </body> 02/06/2006 16:10 58. </html>

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

PHP [fin]

4. 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 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.d 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"> 6. var url = "getCityState.php?param="; // The server-side script function handleHttpResponse() { if (http.readyState == 4 7. function updateCityState() { 8. var zipValue = document.getElementById("zip").value; http.open("GET", url + escape(zipValue), 9. 10. } 11. function getHTTPObject() { 12. var xmlhttp; 13. /*@cc_on 14. @if (@_jscript_version >= 5) 15. try { 16. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 17. } catch (e) { 18. try { 19. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 20. } catch (E) { 21. xmlhttp = false; 22. } 23. } 24. @else 25. xmlhttp = false; 26. @end @*/ 27. if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 28. try { 29. xmlhttp = new XMLHttpRequest(); 30. } catch (e) { 31. xmlhttp = false; 32. } 33. } 34. return xmlhttp; 35. } 36. var http = getHTTPObject(); // We create the HTTP Object 37. </script> 38. </head> 39. <body> 40. <form action="post"> 41. <p> 42. ZIP code: 43. <input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" /> 44. </p> 45. City: 46. <input type="text" name="city" id="city" /> 47. State: 48. <input type="text" size="2" name="state" id="state" /> 49. </form> 50. </body> 51. </html>

5 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

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]

1. <?php 2. echo "Buzzard Puckey,NM"; 3. ?>


PHP [fin]

5. 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]

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

# # TABLE structure FOR TABLE `zipcodes` # CREATE TABLE `zipcodes` ( `zipcode` mediumINT(9) NOT NULL DEFAULT '0', `city` TINYTEXT NOT NULL, `state` char(2) NOT NULL DEFAULT '', `areacode` smallINT(6) NOT NULL DEFAULT '0', PRIMARY KEY (`zipcode`), UNIQUE KEY `zipcode_2` (`zipcode`), KEY `zipcode` (`zipcode`) ) TYPE=MyISAM;
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. 1. Select the zipcodes table in PhpMyAdmin to bring up its corresponding page. 2. Scroll to the bottom of the zipcodes table page and look for a link that says "Insert data from a textfile into table". 3. Click on the "Insert data from a textfile into table" link . 4. 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: 5. PhpMyAdmin Graphic Click the "Submit" button

6. 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 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

1. <?php 2. /** 3. * Connects to the database. 4. * Return false if connection failed. 5. * Be sure to change the $database_name. $database_username , and 6. * $database_password values to reflect your database settings. 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); 19. if (! $result) return false; 20. if (! mysql_select_db($database_name)) return false; 21. return $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); 29. if ( $count > 0) { 30. $city = mysql_result($result,0,'city'); 31. $state = mysql_result($result,0,'state'); 32. } 33. } 34. if (isset( $city) && isset($state)) { 35. $return_value = $city . "," . $state; 36. } 37. else { 38. $return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes 39. } 40. echo $return_value; // This will become the response value for the XMLHttpRequest object 41. ?>

7 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

PHP [fin] 7. Room for Improvement In our haste to get our code up and running, we have neglected the following scenarios: 1. Invalid ZIP codes are typed in. 2. The visitor's browser does not support the XMLHttpRequest object. 3. A request is made before the last request has completed.

Lets make ourselves feel all warm and fuzzy inside and add the highlighted code below to our HTML file: PHP [inicio]

8 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

9 de 14

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.d 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"> 6. var url = "getCityState.php?param="; // The server-side script 7. function handleHttpResponse() { 8. if ( http.readyState == 4) { 9. 10. if ( 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. } 24. var isWorking = false; 25. 26. function updateCityState() { 27. 28. if (! isWorking && http) { 29. 30. var 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. } 41. function getHTTPObject() { 42. var xmlhttp; 43. /*@cc_on 44. @if (@_jscript_version >= 5) 45. try { 46. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 47. } catch (e) { 48. try { 49. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 50. } catch (E) { 02/06/2006 16:10 51. xmlhttp = false;

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

PHP [fin]

8. 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 . 1. We first comment out line #29 which was the old way of packaging the city and state data. 2. 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. 3. 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]

10 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

1. <?php 2. /** 3. * Connects to the database. 4. * Return false if connection failed. 5. * Be sure to change the $database_name. $database_username , and 6. * $database_password values to reflect your database settings. 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); 13. if (! $result) return false; 14. if (! mysql_select_db($database_name)) return false; 15. return $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); 23. if ( $count > 0) { 24. $city = mysql_result($result,0,'city'); 25. $state = mysql_result($result,0,'state'); 26. } 27. } 28. if (isset( $city) && isset($state)) { 29. // $return_value = $city . "," . $state; 30. $return_value = '<?xml version="1.0" standalone="yes"?><zip><city>' .$city.'</city><state>' 31. 32. } 33. else { 34. $return_value = "invalid".",".$_GET['param']; // Include Zip for debugging purposes 35. } 36. header('Content-Type: text/xml'); 37. 38. echo $return_value; // This will become the response value for the XMLHttpRequest object 39. ?>
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.

11 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

PHP [inicio]

12 de 14

02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

13 de 14

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.d 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"> 6. var url = "getCityState.php?param="; // The server-side script 7. function handleHttpResponse() { 8. if ( http.readyState == 4) { 9. if ( http.responseText.indexOf('invalid') == -1) { 10. // Use the XML DOM to unpack the city and state data var xmlDocument = http.responseXML; var city = xmlDocum 11. 12. document.getElementById('city').value = city; 13. document.getElementById('state').value = state; 14. isWorking = false; 15. } 16. } 17. } 18. var isWorking = false; 19. function updateCityState() { 20. if (! isWorking && http) { 21. var 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. } 28. function getHTTPObject() { 29. var xmlhttp; 30. /*@cc_on 31. @if (@_jscript_version >= 5) 32. try { 33. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 34. } catch (e) { 35. try { 36. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 37. } catch (E) { 38. xmlhttp = false; 39. } 40. } 41. @else 42. xmlhttp = false; 43. @end @*/ 44. if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 45. try { 46. xmlhttp = new XMLHttpRequest(); 47. xmlhttp.overrideMimeType("text/xml"); 48. } 02/06/2006 16:10

Leimnud Sistema de Manuales-Tutorial bsico del mtodo AJAX con...

file:///D:/Tutoriales/Tutorial%20b%E1sico%20del%20m%E9todo%2...

PHP [fin]

9. 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.

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)

14 de 14

02/06/2006 16:10

You might also like