JavaScript
  Home arrow JavaScript arrow Page 4 - Working with AJAX and the Prototype JavaSc...
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 
Sun Developer Network 
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

Working with AJAX and the Prototype JavaScript Library
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2007-02-06

    Table of Contents:
  • Working with AJAX and the Prototype JavaScript Library
  • Using the Prototype/AJAX combination
  • Dealing with formatted (X)HTML results
  • Using the Try.these() function and the each loop

  • 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


    Working with AJAX and the Prototype JavaScript Library - Using the Try.these() function and the each loop


    (Page 4 of 4 )

    Among the wealth of functions that come packaged with Prototype, there's one that can be particularly useful in those cases where you need to execute different JavaScript routines, depending on the browser in which they're running.

    In this case, I'm referencing to the "Try.these()" function, which will test different code blocks specified as parameters, and only execute the one that works. Also, these code blocks, which are wrapped up in functions, are evaluated in the order in which they're specified, as the below example clearly shows. Take a look at it, please:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <title>Example Try.these() function</title>
    <script language="javascript" src="prototype-1.4.0.js"></script>
    <script language="javascript">
    // example using Try.these() function - returns a cross-browser
    request object
    function getHttpRequestObject(){
       return Try.these(
         function(){return new XMLHttpRequest();},
         function(){return new ActiveXObject("Microsoft.XMLHTTP");}
       )
    }
    window.onload=function(){
       if(document.getElementById && document.createElement &&
    document.getElementsByTagName){
         var xmlobj=getHttpRequestObject();
         alert(xmlobj);
       }
    }
    </script>
    </head>
    <body>
     
    <h1>Example using Try.these() function</h1>
    </body>
    </html>

    As you can see, the above example demonstrates in a friendly fashion how the "Try.these()" function can be used to create a cross-browser HTTP requester object. Here, and depending on the browser where the previous script will be executed, one of the two functions specified as arguments will work successfully, in this way returning the type of object fully supported by the client. Pretty simple, isn't it?

    Of course, I'm sure that you'll find more useful examples where the "Try.these()" function can be utilized, therefore let me leap forward and show you another handy feature included with the Prototype library for working easily with iterators.

    The "each()" function allows you to quickly traverse any enumerable object, like array structures, among others. Logically, the implementation of this function can be grasped more easily if you take a look at the following example. It uses a conventional "for" loop to traverse an array of DIVs.

    That said, the corresponding code sample is the following: 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <title>Example of conventional loop</title>
    <script language="javascript" src="prototype-1.4.0.js"></script>
    <script language="javascript">
    // example using conventional loop
    function displayHTML(){
       var divs=document.getElementsByTagName('div');
       for(var i=0;i<divs.length;i++){
         var htmlcont=document.getElementById('htmlcontainer');
         htmlcont.innerHTML+=divs[i].innerHTML;
       }
    }
    window.onload=function(){
       if(document.getElementById && document.createElement &&
    document.getElementsByTagName){
         var btn=$('testbutton');
         if(!btn){return};
         btn.onclick=displayHTML;
       }
    }
    </script>
    </head>
    <body>
     
    <div>
       
    <p>This is a sample paragraph, which is wrapped by the first
    DIV</p>
     
    </div>
     
    <div>
       
    <p>This is a sample paragraph, which is wrapped by the
    second DIV</p>
     
    </div>
     
    <div>
       
    <p>This is a sample paragraph, which is wrapped by the third
    DIV</p>
     
    </div>
     
    <div id="htmlcontainer"></div>
     
    <input type="button" value="Show function result"
    id="testbutton" />
    </body>
    </html>

    All right, now that you hopefully recalled how to use a regular "for" loop, pay attention to the example below, which demonstrates the use of the "each()" function that I mentioned previously:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <title>Example of each loop</title>
    <script language="javascript" src="prototype-1.4.0.js"></script>
    <script language="javascript">
    // example using each loop
    function displayHTML(){
       var divs=$A(document.getElementsByTagName('div'));
       divs.each(function(div){alert(div.innerHTML);});
    }
    window.onload=function(){
       if(document.getElementById && document.createElement &&
    document.getElementsByTagName){
         var btn=$('testbutton');
         if(!btn){return};
         btn.onclick=displayHTML;
       }
    }
    </script>
    </head>
    <body>
     
    <div>
       
    <p>This is a sample paragraph, which is wrapped by the first
    DIV</p>
     
    </div>
     
    <div>
       
    <p>This is a sample paragraph, which is wrapped by the
    second DIV</p>
     
    </div>
     
    <div>
       
    <p>This is a sample paragraph, which is wrapped by the third
    DIV</p>
     
    </div>
     
    <input type="button" value="Show function result"
    id="testbutton" />
    </body>
    </html>

    Wasn't that great? As you can see, the above example first fetches an array of DIVs, and then uses the "each()" function to iterate over them. Of course, at first glance, the syntax that corresponds to this function may look a bit strange, but those developers that work frequently with Ruby will find it very familiar.

    True to form, the previous example is rather primitive, but you should notice one important thing concerning the use of the "each()" function. As you saw, I specified a function to be called inside the loop, a fact demonstrated by the following line of code:

      divs.each(function(div){alert(div.innerHTML);});

    This function is called an "iterator function," and it can be used with any enumerable object to perform a specific task on the object in question. Nevertheless, this certainly will be one of the topics that will be discussed in the last tutorial of the series. For the moment, have some fun using the recently-discovered "each()" loop. Happy coding!

    Final thoughts

    In this second installment of the series, I took a quick look at the AJAX module that comes integrated with Prototype, undoubtedly one of its strongest points. Besides, I offered a simple introduction to the "Try.these()" and "each()" functions, something that should give you a clearer idea of the capacity of this library for working with iterators.

    Nonetheless, iterators and other useful features will be properly covered in the last part of the series, so I hope to see you there!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · In this second part of the series, you'll learn how to use the excellent AJAX...
     

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT