JavaScript
  Home arrow JavaScript arrow Page 3 - Creating a Dynamic Banner System with AJAX
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
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? 
JAVASCRIPT

Creating a Dynamic Banner System with AJAX
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 10
    2007-07-30

    Table of Contents:
  • Creating a Dynamic Banner System with AJAX
  • Creating a system of dynamic banners
  • Displaying the banners on the browser using AJAX
  • Completing the dynamic banner system
  • Listing the banner application's full source code

  • 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


    Creating a Dynamic Banner System with AJAX - Displaying the banners on the browser using AJAX


    (Page 3 of 5 )

    As I said in the previous section, fetching the corresponding banners from the web server, as well as showing them on the browser in a predefined sequence, are all well-differentiated tasks that will be performed by a pair of straightforward JavaScript functions whose signatures are shown below. Take a look at them, please:

    // send http requests
    function sendHttpRequest(url,callbackFunc,respXml){
      
    var xmlobj=null;
       try{
         xmlobj=new XMLHttpRequest();
       }
       catch(e){
       try{
         xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
       }
       catch(e){
         alert('AJAX is not supported by your browser!');
         return false;
       }
    }
    xmlobj.onreadystatechange=function(){
      if(xmlobj.readyState==4){
        if(xmlobj.status==200){
          respXml?eval(callbackFunc+'(xmlobj.responseXML)'):eval
    (callbackFunc+'(xmlobj.responseText)');
        }
      }
    }
    // open socket connection
    xmlobj.open('GET',url,true);
    // send http header
    xmlobj.setRequestHeader('Content-Type','text/plain; charset=UTF-
    8');
    // send http request
    xmlobj.send(null);
    }
    // display banners
    function displayBanner(bannerData){
       // parse banner data
       var bannerImg=bannerData.split('|')[0];
       if(!bannerImg){return};
       var bannerUrl=bannerData.split('|')[1];
       if(!bannerUrl){return};
       var bannerCont=document.getElementById('bannercontainer');
       if(!bannerCont){return};
       // clean up banner container
       bannerCont.innerHTML='';
       // create banner link
       var a=document.createElement('a');
       a.setAttribute('href',bannerUrl);
       // create banner image
       var img=document.createElement('img');
       // set banner image dimensions
       img.setAttribute('src',bannerImg);
       img.setAttribute('width',180);
       img.setAttribute('height',400);
       // append banner image to link
       a.appendChild(img);
       // append banner link to container
       bannerCont.appendChild(a);
       // increase banner counter
       bannerId++;
       if(bannerId>2){bannerId=0};
       // fetch banners recursively 
       setTimeout("sendHttpRequest('fetchbanner.php?
    bannerid="+bannerId+"','displayBanner')",15*1000);
    }
    // initialize banner counter
    bannerId=0;
    window.onload=function(){
      if(document.getElementById&&document.
    getElementsByTagName&&document.createElement){
        // display first banner
        sendHttpRequest('fetchbanner.php?
    bannerid='+bannerId,'displayBanner');
      }
    }

    If you take some time and study the above JavaScript code, then you'll quickly grasp how it works, since it's actually very easy to follow. As you can see, I defined two primary functions, named "sendHttpRequests()" and "displayBanner()" respectively. The first one is responsible for fetching the dynamic banners via an HTTP request object from the web server, and the second one is tasked with displaying them directly on the browser.

    Besides, you should notice that the "displayBanner()" function will retrieve the image of each banner and its respective URL by splitting the server response into two different parts, a process that can be clearly understood by the following lines of code:

    // parse banner data
    var bannerImg=bannerData.split('|')[0];
    if(!bannerImg){return};
    var bannerUrl=bannerData.split('|')[1];
    if(!bannerUrl){return};

    And finally, the last thing to stress concerning the tasks performed by this useful JavaScript function is that it will fetch from the web server a different banner every 15 seconds by using a typical JavaScript timer like the one shown below:

    setTimeout("sendHttpRequest('fetchbanner.php?
    bannerid="+bannerId+"','displayBanner')",15*1000);

    Definitely, you'll have to agree with me that displaying a bunch of dynamic banners with AJAX is a no-brainer process which can be achieved with a minimal background in HTTP request objects, right?

    So far, so good. At this time I'm pretty certain that you have grasped the logic that drives this AJAX-based application, whose primary function is to display on the browser a group of dynamic banners based upon a predetermined time sequence. The only missing piece of this schema is the development of a server-side script that sends to the client each requested banner image, along with its URL.

    As you might have guessed after analyzing the previous JavaScript code, this script will reside in a PHP file called "fetchbanner.php." Its definition will be shown in detail in the following section, so click on the link that appears below and keep reading.

    More JavaScript Articles
    More By Alejandro Gervasio


       · If you're a web developer who wants to find other uses for AJAX, this series...
     

    JAVASCRIPT ARTICLES

    - Comparing Fields and Customizing Error Messa...
    - Checking Numbers and File Extensions with jQ...
    - Validating Digits and Dates with jQuery`s Va...
    - Validating Ranges, Emails, and URLs with jQu...
    - More Uses for the jQuery Tooltip Plug-in`s b...
    - Building Image-Based Tooltips with the jQuer...
    - Using the jQuery Tooltip Plug-in`s bodyHandl...
    - Using Rangelength, Min and Max with the Vali...
    - Using Minlength and Maxlength with the Valid...
    - Modifying Tooltip Coordinates with the jQuer...
    - Applying a Fade Out Effect with the jQuery T...
    - Tracking Mouse Movements with the jQuery Too...
    - Checking Online Forms with the Validator jQu...
    - Nested JavaScript Functions as Objects
    - The jQuery Tooltip Plug-in







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek