Miscellaneous
  Home arrow Miscellaneous arrow Page 3 - Quick and Dirty AJAX Tutorial
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MISCELLANEOUS

Quick and Dirty AJAX Tutorial
By: notepad
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 14
    2006-11-14

    Table of Contents:
  • Quick and Dirty AJAX Tutorial
  • AJAX Basics
  • A More Advanced Approach
  • Things to Consider

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Quick and Dirty AJAX Tutorial - A More Advanced Approach


    (Page 3 of 4 )

    To give a more real-world example of how AJAX can be used, consider the following revised AJAX:

    <script type="text/javascript">
    function createRequestObject() {
      var ro;
      var browser = navigator.appName;
      if(browser == 'Microsoft Internet Explorer') {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
      } else {
        ro = new XMLHttpRequest();
      }
      return ro;
    }

    function handleTimestamp() {
      if(map.handleTimestamp.ajax.readyState == 4) {
        var response = map.handleTimestamp.ajax.responseText;
        if(response != timestamp) {
          timestamp = response;
        }
      }
    }

    function handleFoo() {
      if(map.handleUsersOnline.ajax.readyState == 4) {
        var response = map.handleFoo.ajax.responseText;
        if(response != 'noupdate') {
          document.getElementById('foo').innerHTML = response;
        }
      }
    }

    var map = {
      handleTimestamp:{
        ajax: createRequestObject(),
        handler: handleTimestamp
      },
      handleFoo:{
        ajax: createRequestObject(),
        handler: handleFoo
      }
    };

    function sndReq(timestamp, action) {
      map[action].ajax.open('get', 'ajax.php?time='+timestamp+
        '&action='+action+'&nocache='+Date());
      map[action].ajax.onreadystatechange = map[action].handler
      map[action].ajax.send(null);
    }

    function reqUpdates(timestamp) {
      sndReq(timestamp, 'handleTimestamp');
      sndReq(timestamp, 'handleFoo');
    }

    var timestamp = '<?php echo time(); ?>';
    setInterval("reqUpdates(timestamp)", 30000);
    </script>

    Woo! That's a lot of revisions, eh? The createRequestObject() is the same, except we're no longer assigning it to an http variable because we want each div being updated to have its own request object (to prevent conflicting data). For the same reason, we're using JavaScripts map to help divide everything up. So now instead of having one handleResponse() function, we can create a separate handler function for each thing we want to update.

    In the above example we have two handler functions, handleTimestamp(), and handleFoo(). Also note the addition of the line:

    var timestamp = '<?php echo time(); ?>';

    Here we set a JavaScript variable with the value of the current server time. We can use this timestamp to check if there are any new updates in our database. If there are new updates, then not only will we instruct handleFoo() to display them for our visitors, but handleTimestamp() will update our JavaScript timestamp variable so we can start over and only send fresh content! MMmm it's like I just ate a breath-mint, so fresh...

    You will also notice some revisions to our sndReq() function, which now sends a query string to our ajax.php page to work with. The timestamp variable, as mentioned, will help determine what content is new. The action variable will determine what we're updating (what div, for example). The nocache variable in the query string is being set with the current JavaScript (or client-side) time in order to prevent certain browsers from calling a cached version of the page, as obviously that would be bad.

    Now onto the revised ajax.php:

    <?php
    if(isset($_REQUEST['time'], $_REQUEST['action'])) {
      
    // never trust client-side data
      
    $timestamp ctype_digit($_REQUEST['time']) ? 
        
    $_REQUEST['time'] : time();

      switch(
    $_REQUEST['action']) {
      case 
    'handleTimestamp':
        echo 
    time();
        break;
            
      case 
    'handleFoo':
        
    $link mysql_connect('localhost''mysql_user'
          
    'mysql_password');
        
    $query "SELECT * FROM mysql_table WHERE UNIX_TIMESTAMP(
    date_field) > '$timestamp'"
    ;
        
    $result mysql_query($query);
        if(
    mysql_num_rows($result) &gt0) {
          
    // output your updates
        
    } else {
          echo 
    'noupdate';
        }
        
    mysql_close($link);
        break;
      }
      exit();
    }
    ?>

    This should be pretty straight forward. First, since we're going to be using our timestamp in a database query, we want to make sure it's actually a numerical value to prevent some type of injection attack. Next we enter into a switch loop to determine what code to execute, depending on what action is being called. The case handleFoo is what should really interest you, as you can see how easy it is to check for new updates knowing we will always have a current timestamp. If no updates are available, we just send the text "noupdate" which our JavaScript will use to process accordingly.

    If you want to update an additional div, simply add a new handler function to the JavaScript and follow the same syntax as the other two existing ones. The same goes for updating ajax.php.

    More Miscellaneous Articles
    More By notepad


     

    MISCELLANEOUS ARTICLES

    - Stopping CSRF Attacks in Your PHP Applicatio...
    - Quick and Dirty AJAX Tutorial
    - Flickr Puzzle Mashup
    - The PAVISE of Security
    - Creating a CAPTCHA with PHP
    - Sending SMS Thru HTTP
    - The Postal Fix - Part 2
    - Adding Mail with Exim
    - The Postal Fix - Part 1
    - Create Your Own Custom API
    - Adding Drop Shadows with PHP
    - Writing a Basic Authentication System in PHP
    - Overlapping Images with GD
    - Using Sockets in PHP
    - Dynamic CSS with PHP






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway