Miscellaneous

  Home arrow Miscellaneous arrow Page 3 - Quick and Dirty AJAX Tutorial
MISCELLANEOUS

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

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

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    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

    blog comments powered by Disqus

    MISCELLANEOUS ARTICLES

    - Oracle Database XE: Indexes and Sequences
    - Modifying Tables in Oracle Database XE
    - Oracle Database XE: Tables and Constraints
    - More on Oracle Databases and Datatypes
    - Oracle Database XE Datatypes: Datetime and L...
    - Oracle Database XE Datatypes: Character and ...
    - From Databases to Datatypes
    - Firefox 3.6.6 Released with Improved Plug-in...
    - Attention Bloggers: WordPress 3.0 Now Releas...
    - Reflection in PHP 5
    - Inheritance and Other Advanced OOP Features
    - Advanced OOP Features
    - Linux from Scratch V.6.6 Review
    - Linux Gaining in Strength
    - Install Slackware on Your Old PC


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap