Ajax Made Easier With Prototype.js

Discussion in 'JavaScript and AJAX' started by pradeep, Jul 30, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in

    Introduction



    Ajax, or AJAX, is a web development technique used for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user requests a change. This is intended to increase the web page's interactivity, speed, functionality, and usability.

    Conventional JavaScript for Ajax would look something like Form validation with PHP & JavaScript. Plus, you'll have to check for browser compatibility, you'll have to code for error handling.

    Prototype.js



    How easy would it been if there was some API or something similar?? Well, we're lucky to have prototype.js.
    The Prototype JavaScript Framework is a JavaScript framework that provides an Ajax framework and other utilities. Though available as a standalone library, Ruby on Rails integrates the framework as well as other projects such as script.aculo.us and Rico.
    You can download it from http://www.prototypejs.org/

    Easier Ajax Coding



    An Example:
    Code:
     var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype');
     // notice the use of a proxy to circumvent the Same Origin Policy.
     
     new Ajax.Request(url, {
       method: 'get',
       onSuccess: function(transport) {
         var notice = $('notice');
         if (transport.responseText.match(/href="http:\/\/prototypejs.org/))
           notice.update('Yeah! You are in the Top 10!').setStyle({ background: '#dfd' });
         else
           notice.update('Damn! You are beyond #10...').setStyle({ background: '#fdd' });
       }
     });
     
    You can access the Protoype.js API documentation online; for Ajax at http://www.prototypejs.org/api/ajax/request

    A Simple Implementation



    We'll create a HTML page, where when you input a number it'll fetch the number in words using Ajax. The PHP script which returns the number in words uses the PEAR package Number_Words (http://pear.php.net/package/Numbers_Words) to generate the number in words.

    The HTML:
    HTML:
     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
     <HTML>
     <HEAD>
     <TITLE>Ajax Made Easier With Prototype.js</TITLE>
     <META NAME="Author" CONTENT="S Pradeep">
     <META NAME="Keywords" CONTENT="ajax,php,web programming,prototype.js,JavaScript">
     <META NAME="Description" CONTENT="Ajax Made Easier With Prototype.js">
     <script language='JavaScript' src='../resources/prototype.js'></script>
     <style>
     .msg-box
     {
         border:#666 1px solid;
         background:#eee;
         text-align:center;
     }
     </style>
     <script language='JavaScript'>
     // Let's write the JavaScript
     // The form submit handler
     Event.observe(window,'load',function(e)
     {
         Event.observe(document.forms[0],'submit',handleSubmit); // element to observer,event,callback function
     });
     
     function handleSubmit(evt)
     {
         var frm = Event.element(evt);
         var elements = frm.elements;
         // Let's do some validation here
         if(!elements['number'].present())
         {
             alert('Please enter a number')
             elements['number'].activate(); // give focus to the number text field
             Event.stop(evt); // Stop the form from submitting
             return;
         }
         else if(isNaN(elements['number'].value)) // check whether the value entered is a number or not
         {
             alert('Please enter a valid number')
             elements['number'].activate().clear(); // give focus to the number text field
             Event.stop(evt); // Stop the form from submitting
             return;
         }
     
         $('MsgBox').hide();
         // All ok, let's fire away the Ajax
         var url = 'number_to_words.php?number='+elements['number'].value;
         new Ajax.Request(url,{
         method: 'get',
         onLoading: function(transport)
         {
             $('MsgBox').show().update('Fetching Data ...');
         },
         onSuccess: function(transport)
         {
             var dr = transport.responseXML.documentElement;
             var s = dr.getElementsByTagName('resultCode')[0].firstChild.data;
             var m = dr.getElementsByTagName('msg')[0].firstChild.data;
             if(s == 1) // success
             {
                 $('MsgBox').show().update(m);
             }
             else // error
                 $('MsgBox').show().update(m);
         },
         onFailure: function(transport)
         {
             // when the request fails
             alert('The request failed');
         },
         onException: function(err)
         {
             // When an exception is encountered while executing the callbacks
             alert('Exception');
         }
         });
     
         Event.stop(evt);
     }
     </script>
     </HEAD>
     <BODY>
     <div class='msg-box'>Enter a number, Ajax will be used to fetch the number in words and display it here.</div>
     <br>
     <form id='NumForm'>
     <fieldset>
         <legend>Number To Words</legend>
         <table border=0>
         <tr><td>Enter Number</td><td><input type="text" name="number"></td></tr>
         <tr><td>&nbsp;</td><td><input type="submit" name="bt" value="Get number in words"></td></tr>
         </table>
     </fieldset>
         <br>
         <div class='msg-box' style="display:none" id="MsgBox"></div>
     </BODY>
     </HTML>
     
    PHP Script: number_to_words.php
    PHP:
     <?
     /*
     **    @file: number_to_words.php
     **    @author: S Pradeep
     **    @version: 0.9
     **    @dependencies: Pear package Numbers_Words
     */
     
     require_once('Numbers/Words.php');
     ob_start(); // Start output buffering
     
     if(!empty($_GET['number']))
     {
         $number = $_GET['number'];
         if(!is_int($number)) // check whether we have an integer to work on
         {
             $nw = new Numbers_Words(); // create an instance of the Pear package Numbers_Words
             $text = $nw->toWords($number);
             // send back the number in words
             _sendResponse(1,$text);
         }
         else // send an error
         {
             _sendResponse(0,'Error: Datatype Mismatch');
         }
     }
     
     // Default response
     _sendResponse(0,'Error: Parameter Missing');
     
     function _sendResponse($code,$msg)
     {
         ob_clean(); // clear the contents of the output buffer
         // The page shouldn't by cached by the browser or proxy
         header('Cache-Control: no-cache, no-store, must-revalidate');
         header('Pragma: no-cache');
         header('Content-Type: text/xml'); // set the content type to XML
     
         printf('<root><resultCode>%d</resultCode><msg>%s</msg></root>',$code,$msg);
         exit(0);
     }
     ?>
     
    View the live, completed example here Ajax Made Easier - Working sample
     
  2. Full Zip Hoody

    Full Zip Hoody New Member

    Joined:
    Sep 29, 2010
    Messages:
    20
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Programer
    Location:
    US of A
    well instead of an API this Prototype.js is good stuff.. not better but good instead of.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice