What is this? From this page you can use the Social Web links to save Simple AJAX example to a social bookmarking site, or the E-mail form to send a link via e-mail.

Social Web

E-mail

E-mail It
February 20, 2009

Simple AJAX example

Posted in: Programming

ajaxOnce I created my first AJAX “application” (also based on some simple tutorial) I just can’t stop thinking of AJAX methodology and it’s usage all over the projects.

What is AJAX actually? By definition – Asynchronous JavaScript and XML, a technique used in web application development.
In general it is a combination of XHTML and JavaScript.


How it works? I think it’s the best to describe through a example:

  • you click on a button which on it’s onClick method calls a JavaScript function (with some parameters)
  • that JS function is using XMLHttpRequest (Mozilla) or Msxml2.XMLHTTP (IE) object which makes a HTTP request back to the server but without refreshing the whole web page
  • that HTTP request could be for example a .PHP script which checks for certain data in MySQL database and returns (“echo”) true/false value
  • at this point you’re back in JS function which does something with that returned true/false value on your HTML form or something else

Those “web 2.0” applications are full of this AJAX, everything is done without refreshing the whole web page each time a visitor makes a click. A perfect (and also a great one) example would be a Gmail.

Here’s a simple example which shows calling of XMLHttpRequest object from a XHTML page and returning the value back to the page:

XHTML page (“xhtml_page.html”)

  1.  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4.  
  5. <head>
  6.    <title>This is my first AJAX example</title>
  7.  
  8.    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  9.  
  10.    <script language="javascript" type="text/javascript" src="ajax_call.js"></script>
  11.    <script type="text/javascript" language="javascript">
  12.         function ajaxGetValueFromServer(objPN) {
  13.             get(objPN);
  14.         }
  15.     </script>
  16. </head>
  17.  
  18. <body>
  19. <form name="my_form" id="my_form" method="post">
  20. <p>
  21.   <input name="my_text_field" type="text" id="my_text_field" />
  22. </p>
  23. <p>
  24.   <input type="button" name="get value" id="get value" value="get random number from server" onclick="ajaxGetValueFromServer(this.parentNode);" />
  25. </p>
  26. </form>
  27. </body>
  28.  
  29. </html>
  30.  

JavaScript functions file (“ajax_call.js”)

  1.  
  2. var http_request = false;
  3.  
  4. function makePOSTRequest(url, parameters) {
  5.    http_request = false;
  6.    if (window.XMLHttpRequest) { // Mozilla, Safari, …
  7.       http_request = new XMLHttpRequest();
  8.       if (http_request.overrideMimeType) {
  9.          // set type accordingly to anticipated content type
  10.          //http_request.overrideMimeType(‘text/xml’);
  11.          http_request.overrideMimeType(‘text/html’);
  12.       }
  13.    }
  14.    else if (window.ActiveXObject) { // check if IE
  15.       try {
  16.          http_request = new ActiveXObject("Msxml2.XMLHTTP");
  17.       }
  18.       catch (e) {
  19.          try {
  20.             http_request = new ActiveXObject("Microsoft.XMLHTTP");
  21.          }
  22.          catch (e) {}
  23.       }
  24.    }
  25.    if (!http_request) {
  26.       window.alert(‘Cannot make call to a XMLHTTP module.’);
  27.       return false;
  28.    }
  29.    
  30.    http_request.onreadystatechange = alertContents;
  31.    http_request.open(‘POST’, url, true);
  32.    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  33.    http_request.setRequestHeader("Content-length", parameters.length);
  34.    http_request.setRequestHeader("Connection", "close");
  35.    http_request.send(parameters);
  36. }
  37.  
  38. function alertContents() {
  39.    if (http_request.readyState == 4) {
  40.       if (http_request.status == 200) {
  41.          result = http_request.responseText;
  42.             document.my_form.my_text_field.value = result;
  43.       }
  44.       else {
  45.          window.alert(‘Error occured.’);
  46.       }
  47.    }
  48. }
  49.  
  50. function get(obj) {
  51.    var poststr = "do_what=return_random_number";
  52.    makePOSTRequest(‘ajax_return_value.php’, poststr);
  53. }
  54.  

PHP processing file (“ajax_return_value.php”)

  1.  
  2. <?php
  3. switch($_POST[‘do_what’]) {
  4.    case ‘return_random_number’:
  5.       srand();
  6.       echo rand(1000, 9999);
  7.       exit;
  8.      break;
  9.  
  10.    default:
  11.       exit;
  12.      break;
  13. }
  14. ?>
  15.  

You can simply copy/paste the code above in three files (as noted), place it on a web server with PHP support and call it through your web browser, and it should work.

Just be careful with that copy/paste because the web browser renders a “different” quote signs…
Or, you can download demo files.

This is a basic of AJAX programming with a PHP on a server-side example.
Once you understand how this works, your next step would be to take a more detailed look on how to handle “multiple clicks” and maybe you’d like to check out some of those existing AJAX frameworks for your next big project…

 


Return to: Simple AJAX example