AJAX Tricks and Prototype

We present a few AJAX tricks and a quick introduction to Prototype. Examples taken from:

1 AJAX

2 Submit Form Text

var formObj = null;
var formObjTyp = "";
var request=null;

//input field's event handlers
window.onload=function(){
    var txtA = document.getElementById("tarea");
    if(txtA != null){
        txtA.onblur=function(){
            if (this.value) { getInfo(this);}};    }

    var tfd = document.getElementById("tfield");
    // tfd.onblur=txtA.onblur;
    if(tfd != null){
        tfd.onblur=function(){
            if (this.value) { getInfo(this);}};  }
}

function getInfo(obj){
    if (obj == null ) { return; }
    formObj=obj;
    formObjTyp =obj.tagName;
    if(formObjTyp == "input" || formObjTyp == "INPUT"){
        formObjTyp = formObjTyp + " "+formObj.type;
    }
    formObjTyp = formObjTyp.toLowerCase();
    var url = "http://www.parkerriver.com/s/webforms?objtype="+
              encodeURIComponent(formObjTyp)+"&val="+ encodeURIComponent(obj.value);
    httpRequest("GET",url,true);
}

//event handler for XMLHttpRequest
function handleResponse(){
    try{
        if(request.readyState == 4){
            if(request.status == 200){
                var resp = request.responseText;
                if(resp != null){
                    var func = new Function("return "+resp);
                    var objt = func();
                    if(formObjTyp == "textarea"){
                        if(formObj != null){
                            formObj.value = objt.Form_field_type +" character count: "+objt.Text_length+"\nWord count: "+
                                            objt.Word_count+"\nServer info: "+objt.Server_info;
                        }
                    }  else if(formObjTyp == "input text"){
                        if(formObj != null){
                            formObj.value = objt.Form_field_type +" # characters: "+objt.Text_length+" Word count: "+objt.Word_count; }
                    }
                }
            } else {
                //request.status is 503  if the application isn't available; 
                //500 if the application has a bug
                alert(
                        "A problem occurred with communicating between the XMLHttpRequest object and the server program.");
            }
        }//end outer if
    } catch (err)   {
        alert(err.name);
        alert("It does not appear that the server is available for this application. Please"+
              " try again very soon. \nError: "+err.message);

    }
}

/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
    try{
        /* Specify the function that will handle the HTTP response */
        request.onreadystatechange=handleResponse;
        request.open(reqType,url,bool);
        request.send(null);
    } catch (errv) {
        alert(
                "The application cannot contact the server at the moment. "+
                "Please try again in a few seconds." );
    }
}
/* Wrapper function for constructing a Request object.
 Parameters:
  reqType: The HTTP request type such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
    //Mozilla-based browsers
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request){
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request){
       initReq(reqType,url,asynch);
    }  else {
        alert("Your browser does not permit the use of all "+
        "of this application's features!");}
}

2.1 Convert Key Example

2.2 Convert Key Example with XML

2.3 Convert Key Example with JSON

2.4 Netbeans and Derby and Ajax

  1. Add the derby.jar library to your project. It was installed under glassfish-v2/javadb/lib.
  2. Here is sample code for the connection:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package edu.sc.cse;
    
    import org.apache.derby.jdbc.*;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DatabaseConnector {
    
        public static Connection getConnection() {
            Connection con = null;
            String driver = "org.apache.derby.jdbc.EmbeddedDriver";
            try {
                Class.forName(driver).newInstance();
    
            } catch (Exception e) {
                System.out.println("Failed to load mySQL driver.");
                return null;
            }
            try {
                //AJAX is the database name. 
                //This is for empty username and password
                //Otherwise append ?username=jmvidal&password=usc
                con = DriverManager.getConnection("jdbc:derby://localhost:1527/AJAX");
    
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return con;
          }
    }
    
    
  3. To import or export a whole table, like zipcodes.del use:
    /*To import my zipcodes.del table */
    CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE
    (null,'ZIPCODES','/full-path-name/zipcodes.del',null,null,null,0)
    
    
    /* To export a table */
    CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE
    (null,'ZIPCODES','/full-path-name/zipcodes.del',null,null,null)
    
    
    
    
  4. To delete all rows use delete from "TABLENAME"
  5. To insert use INSERT INTO TABLE (USERNAME,PASSWORD) VALUES ('jmvidal','usc')
  6. When building statments in JDBC, do not add a ; at the end.

3 Direct Web Remoting

4 Prototype

4.1 Utility Methods

4.2 Ajax Object

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:\/\/" href="http://prototypejs.org/" 
              title="Linkification: http://prototypejs.org/">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' });
  },
  parameters: parametersObject, //contains properties+values which will be sent in request.
  postBody: uploadStuff, //it method=post this is the stuff to upload
  requestHeaders: object, //define your own headers
  onComplete: function (t) {
        //completion does not imply success or failure
    },
  onFailure: function (t) {
      //we failed.
    }
});
Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});
//Send contents of id="text" element to server at url=/items
// use reply to populate id="items" element, by appending child
new Ajax.Updater('items', '/items', {
  parameters: { text: $F('text') },
  insertion: Insertion.Bottom
});
new Ajax.PeriodicalUpdater('items', '/items', {
  method: 'get', 
  frequency: 3, 
  decay: 2
});

4.3 Array

clear [15]
clear() -> Array

Clears the array (makes it empty).

clone [16]
clone() -> newArray

Returns a duplicate of the array, leaving the original array intact.

compact [17]
compact() -> newArray

Returns a new version of the array, without any null/ftp://ftp [18]. values.

each [19]
each(iterator) -> Array

Iterates over the array in ascending numerical index order.

first [20]
first() -> value

Returns the first item in the array, or ftp://ftp [21]. if the array is empty.

flatten [22]
flatten() -> newArray

Returns a “flat” (one-dimensional) version of the array. Nested arrays are recursively injected “inline.” This can prove very useful when handling the results of a recursive collection algorithm, for instance.

from [23]
Array.from(iterable) -> actualArray

Clones an existing array or creates a new one from an array-like collection.

This is an alias for the $A() [24] method. Refer to its page for complete description and examples.

indexOf [25]
indexOf(value) -> position

Returns the position of the first occurrence of the argument within the array. If the argument doesn't exist in the array, returns -1.

inspect [26]
inspect() -> String

Returns the debug-oriented string representation of an array.

last [27]
last() -> value

Returns the last item in the array, or ftp://ftp [28]. if the array is empty.

reduce [29]
reduce() -> Array | singleValue

Reduces arrays: one-element arrays are turned into their unique element, while multiple-element arrays are returned untouched.

reverse [30]
reverse([inline = true]) -> Array

Returns the reversed version of the array. By default, directly reverses the original. If inline is set to false, uses a clone of the original array.

size [31]
size() -> Number

Returns the size of the array.

toArray [32]
toArray() -> newArray

This is just a local optimization of the mixed-in toArray [33] from Enumerable [34].

uniq [35]
uniq() -> newArray

Produces a duplicate-free version of an array. If no duplicates are found, the original array is returned.

without [36]
without(value...) -> newArray

Produces a new version of the array that does not contain any of the specified values.

4.4 Element

addClassName [40]

addClassName(element, className) -> HTMLElement 

Adds a CSS class to element.

addMethods [41]

addMethods([methods])

Takes a hash of methods and makes them available as methods of extended [42] elements and of the Element object.

ancestors [43]

ancestors(element) -> [HTMLElement...]

Collects all of element's ancestors and returns them as an array of extended [44] elements.

classNames [45]

classNames(element) -> [className...]

Returns a new instance of ClassNames, an Enumerable object used to read and write class names of the element.

cleanWhitespace [46]

cleanWhitespace(element) -> HTMLElement

Removes all of element's text nodes which contain only whitespace. Returns element.

descendantOf [47]

descendantOf(element, ancestor) -> Boolean 

Checks if element is a descendant of ancestor.

descendants [48]

descendants(element) -> [HTMLElement...]

Collects all of element's descendants and returns them as an array of extended [49] elements.

down [50]

down(element[, cssRule][, index = 0]) -> HTMLElement | ftp://ftp [51].

Returns element's first descendant (or the n-th descendant if index is specified) that matches cssRule. If no cssRule is provided, all descendants are considered. If no descendant matches these criteria, ftp://ftp [52]. is returned.

empty [53]

empty(element) -> Boolean

Tests whether element is empty (i.e. contains only whitespace).

extend [54]

extend(element)

Extends element with all of the methods contained in Element.Methods [55] and Element.Methods.Simulated [56]. If element is an input, textarea or select tag, it will also be extended with the methods from Form.Element.Methods [57]. If it is a form tag, it will also be extended with Form.Methods [58].

getDimensions [59]

getDimensions(element) -> {height: Number, width: Number}

Finds the computed width and height of element and returns them as key/value pairs of an object.

getElementsByClassName [60]

getElementsByClassName(element, className) -> [HTMLElement...]

Fetches all of element's descendants which have a CSS class of className and returns them as an array of extended [61] elements.

getElementsBySelector [62]

getElementsBySelector(element, selector...) -> [HTMLElement...]

Takes an arbitrary number of CSS selectors (strings) and returns a document-order array of extended [63] children of element that match any of them.

getHeight [64]

getHeight(element) -> Number

Finds and returns the computed height of element.

getStyle [65]

getStyle(element, property) -> String | null

Returns the given CSS property value of element. property can be specified in either of its CSS or camelized form.

getWidth [66]

getWidth(element) -> Number

Finds and returns the computed width of element.

hasClassName [67]

hasClassName(element, className) -> Boolean

Checks whether element has the given CSS className.

hide [68]

hide(element) -> HTMLElement

Hides and returns element.

immediateDescendants [69]

immediateDescendants(element) -> [HTMLElement...]

Collects all of the element's immediate descendants (i.e. children) and returns them as an array of extended [70] elements.

inspect [71]

inspect(element) -> String

Returns the debug-oriented string representation of element.

makeClipping [72]

makeClipping(element) -> HTMLElement

Simulates the poorly supported CSS clip property by setting element's overflow value to 'hidden'. Returns element.

makePositioned [73]

makePositioned(element) -> HTMLElement

Allows for the easy creation of CSS containing block [74] by setting element's CSS position to 'relative' if its initial position is either 'static' or ftp://ftp [75].. Returns element.

match [76]

match(element, selector) -> Boolean

Checks if element matches the given CSS selector.

next [77]

next(element[, cssRule][, index = 0]) -> HTMLElement | ftp://ftp [78].

Returns element's following sibling (or the index'th one, if index is specified) that matches cssRule. If no cssRule is provided, all following siblings are considered. If no following sibling matches these criteria, ftp://ftp [79]. is returned.

nextSiblings [80]

nextSiblings(element) -> [HTMLElement...]

Collects all of element's next siblings and returns them as an array of extended [81] elements.

observe [82]

observe(element, eventName, handler[, useCapture = false]) -> HTMLElement

Registers an event handler on element and returns element.

previous [83]

previous(element[, cssRule][, index = 0]) -> HTMLElement | ftp://ftp [84].

Returns element's previous sibling (or the index'th one, if index is specified) that matches cssRule. If no cssRule is provided, all previous siblings are considered. If no previous sibling matches these criteria, ftp://ftp [85]. is returned.

previousSiblings [86]

previousSiblings(element) -> [HTMLElement...]

Collects all of element's previous siblings and returns them as an array of extended [87] elements.

readAttribute [88]

readAttribute(element, attribute) -> String | null

Returns the value of element's attribute or null if attribute has not been specified.

recursivelyCollect [89]

recursivelyCollect(element, property) -> [HTMLElement...]

Recursively collects elements whose relationship is specified by property. property has to be a property (a method won't do!) of element that points to a single DOM node. Returns an array of extended [90] elements.

remove [91]

remove(element) -> HTMLElement

Completely removes element from the document and returns it.

removeClassName [92]

removeClassName(element, className) -> HTMLElement

Removes element's CSS className and returns element.

replace [93]

replace(element[, html]) -> HTMLElement

Replaces element by the content of the html argument and returns the removed element.

scrollTo [94]

scrollTo(element) -> HTMLElement

Scrolls the window so that element appears at the top of the viewport. Returns element.

setStyle [95]

setStyle(element, styles) -> HTMLElement

Modifies element's CSS style properties. Styles are passed as a hash of property-value pairs in which the properties are specified in their camelized form.

show [96]

show(element) -> HTMLElement

Displays and returns element.

siblings [97]

siblings(element) -> [HTMLElement...]

Collects all of element's siblings and returns them as an array of extended [98] elements.

stopObserving [99]

stopObserving(element, eventName, handler) -> HTMLElement

Unregisters handler and returns element.

toggle [100]

toggle(element) -> HTMLElement

Toggles the visibility of element.

toggleClassName [101]

toggleClassName(element, className) -> HTMLElement

Toggles element’s CSS className and returns element.

undoClipping [102]

undoClipping(element) -> HTMLElement

Sets element's CSS overflow property back to the value it had before Element.makeClipping() was applied. Returns element.

undoPositioned [103]

undoPositioned(element) -> HTMLElement

Sets element back to the state it was before Element.makePositioned was applied to it. Returns element.

up [104]

up([cssRule][, index = 0]) -> HTMLElement | ftp://ftp [105].

Returns element's first ancestor (or the index'th ancestor, if index is specified) that matches cssRule. If no cssRule is provided, all ancestors are considered. If no ancestor matches these criteria, ftp://ftp [106]. is returned.

update [107]

update(element[, newContent]) -> HTMLElement

Replaces the content of element with the provided newContent argument and returns element.

visible [108]

visible(element) -> Boolean

Returns a Boolean indicating whether or not element is visible (i.e. whether its inline style property is set to "display: none;").

4.5 Enumerable

4.6 Event

4.7 String

4.8 Template

// the template (our formatting expression)
var myTemplate = new Template('The TV show #{title} was created by #{author}.');

// our data to be formatted by the template
var show = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };


myTemplate.evaluate(show) [120]

URLs

  1. Ajax Hacks, http://www.amazon.com/exec/obidos/ASIN/0596101694/multiagentcom/
  2. Ajax on Java, http://www.amazon.com/exec/obidos/ASIN/0596101872/multiagentcom/
  3. Prototype API Docs, http://www.prototypejs.org/api
  4. Jesse James, Feb. 2005, http://www.adaptivepath.com/publications/essays/archives/000385.php
  5. Ajaxian, http://www.ajaxian.com
  6. jdom, http://www.jdom.org
  7. dom4j, http://www.dom4j.org
  8. json java generators, http://www.json.org
  9. JSON.simple, http://www.json.org/java/json_simple.zip
  10. derby, http://db.apache.org/derby/docs/dev/getstart/
  11. tutorial, http://www.netbeans.org/kb/55/derby-demo.html
  12. DWR, http://getahead.ltd.uk/dwr/
  13. getting started tutorial, http://getahead.org/dwr/getstarted
  14. Jakarta Commons Logging library, http://commons.apache.org/downloads/download_logging.cgi
  15. clear, http://www.prototypejs.org/api/array/clear
  16. clone, http://www.prototypejs.org/api/array/clone
  17. compact, http://www.prototypejs.org/api/array/compact
  18. ftp://ftp, ftp://ftp
  19. each, http://www.prototypejs.org/api/array/each
  20. first, http://www.prototypejs.org/api/array/first
  21. ftp://ftp, ftp://ftp
  22. flatten, http://www.prototypejs.org/api/array/flatten
  23. from, http://www.prototypejs.org/api/array/from
  24. $A(), http://www.prototypejs.org/api/utility/dollar-a
  25. indexOf, http://www.prototypejs.org/api/array/indexof
  26. inspect, http://www.prototypejs.org/api/array/inspect
  27. last, http://www.prototypejs.org/api/array/last
  28. ftp://ftp, ftp://ftp
  29. reduce, http://www.prototypejs.org/api/array/reduce
  30. reverse, http://www.prototypejs.org/api/array/reverse
  31. size, http://www.prototypejs.org/api/array/size
  32. toArray, http://www.prototypejs.org/api/array/toarray
  33. http://www.prototypejs.org/api/enumerable/toArray
  34. http://www.prototypejs.org/api/enumerable
  35. uniq, http://www.prototypejs.org/api/array/uniq
  36. without, http://www.prototypejs.org/api/array/without
  37. Element.getDimensions($('list')).width, javascript:alert(Element.getDimensions($('list')).width)
  38. $('list').getDimensions().width, javascript:alert($('list').getDimensions().width)
  39. $('list').getWidth(), javascript:alert($('list').getWidth())
  40. addClassName, http://www.prototypejs.org/api/element/addClassName
  41. addMethods, http://www.prototypejs.org/api/element/addMethods
  42. http://www.prototypejs.org/api/element/extend
  43. ancestors, http://www.prototypejs.org/api/element/ancestors
  44. extended, http://www.prototypejs.org/api/element/extend
  45. classNames, http://www.prototypejs.org/api/element/classNames
  46. cleanWhitespace, http://www.prototypejs.org/api/element/cleanwhitespace
  47. descendantOf, http://www.prototypejs.org/api/element/descendantOf
  48. descendants, http://www.prototypejs.org/api/element/descendants
  49. extended, http://www.prototypejs.org/api/element/extend
  50. down, http://www.prototypejs.org/api/element/down
  51. ftp://ftp, ftp://ftp
  52. ftp://ftp, ftp://ftp
  53. empty, http://www.prototypejs.org/api/element/empty
  54. extend, http://www.prototypejs.org/api/element/extend
  55. Element.Methods, http://www.prototypejs.org/api/element/methods
  56. Element.Methods.Simulated, http://www.prototypejs.org/api/element/methods/simulated
  57. Form.Element.Methods, http://www.prototypejs.org/api/form/element
  58. Form.Methods, http://www.prototypejs.org/api/form
  59. getDimensions, http://www.prototypejs.org/api/element/getDimensions
  60. getElementsByClassName, http://www.prototypejs.org/api/element/getElementsByClassName
  61. extended, http://www.prototypejs.org/api/element/extend
  62. getElementsBySelector, http://www.prototypejs.org/api/element/getelementsbyselector
  63. extended, http://www.prototypejs.org/api/element/extend
  64. getHeight, http://www.prototypejs.org/api/element/getheight
  65. getStyle, http://www.prototypejs.org/api/element/getStyle
  66. getWidth, http://www.prototypejs.org/api/element/getWidth
  67. hasClassName, http://www.prototypejs.org/api/element/hasClassName
  68. hide, http://www.prototypejs.org/api/element/hide
  69. immediateDescendants, http://www.prototypejs.org/api/element/immediateDescendants
  70. extended, http://www.prototypejs.org/api/element/extend
  71. inspect, http://www.prototypejs.org/api/element/inspect
  72. makeClipping, http://www.prototypejs.org/api/element/makeClipping
  73. makePositioned, http://www.prototypejs.org/api/element/makePositioned
  74. CSS containing block, http://www.w3.org/TR/CSS21/visudet.html#containing-block-details
  75. ftp://ftp, ftp://ftp
  76. match, http://www.prototypejs.org/api/element/match
  77. next, http://www.prototypejs.org/api/element/next
  78. ftp://ftp, ftp://ftp
  79. ftp://ftp, ftp://ftp
  80. nextSiblings, http://www.prototypejs.org/api/element/nextSiblings
  81. extended, http://www.prototypejs.org/api/element/extend
  82. observe, http://www.prototypejs.org/api/element/observe
  83. previous, http://www.prototypejs.org/api/element/previous
  84. ftp://ftp, ftp://ftp
  85. ftp://ftp, ftp://ftp
  86. previousSiblings, http://www.prototypejs.org/api/element/previousSiblings
  87. extended, http://www.prototypejs.org/api/element/extend
  88. readAttribute, http://www.prototypejs.org/api/element/readAttribute
  89. recursivelyCollect, http://www.prototypejs.org/api/element/recursivelyCollect
  90. extended, http://www.prototypejs.org/api/element/extend
  91. remove, http://www.prototypejs.org/api/element/remove
  92. removeClassName, http://www.prototypejs.org/api/element/removeClassName
  93. replace, http://www.prototypejs.org/api/element/replace
  94. scrollTo, http://www.prototypejs.org/api/element/scrollto
  95. setStyle, http://www.prototypejs.org/api/element/setStyle
  96. show, http://www.prototypejs.org/api/element/show
  97. siblings, http://www.prototypejs.org/api/element/siblings
  98. extended, http://www.prototypejs.org/api/element/extend
  99. stopObserving, http://www.prototypejs.org/api/element/stopobserving
  100. toggle, http://www.prototypejs.org/api/element/toggle
  101. toggleClassName, http://www.prototypejs.org/api/element/toggleClassName
  102. undoClipping, http://www.prototypejs.org/api/element/undoClipping
  103. undoPositioned, http://www.prototypejs.org/api/element/undoPositioned
  104. up, http://www.prototypejs.org/api/element/up
  105. ftp://ftp, ftp://ftp
  106. ftp://ftp, ftp://ftp
  107. update, http://www.prototypejs.org/api/element/update
  108. visible, http://www.prototypejs.org/api/element/visible
  109. ['Hitch', "Hiker's", 'Guide', 'To', 'The', 'Galaxy'].collect(, javascript:alert(['Hitch', 'Hikers', 'Guide', 'To', 'The', 'Galaxy'].collect(function(s) { return s.charAt(0).toUpperCase();}).join(''))
  110. $R(1,5).collect(function(n) {return n * n;}), javascript:alert($R(1,5).collect(function(n) {return n * n;}))
  111. ['hello','world','this','is','nice'].find(function(s) {return s.length == 4;}), javascript:alert(['hello','world','this','is','nice'].find(function(s) {return s.length == 4;}))
  112. $R(1,30).grep(/[05]$/), javascript:alert($R(1,30).grep(/[05]$/))
  113. $R(1,10).max(), javascript:alert($R(1,10).max())
  114. $R(1, 10).partition(function(n) {, javascript:alert($R(1, 10).partition(function(n) { return 0 == n % 2;}))
  115. ['hello', 'world', 'this', 'is', 'nice'].sortBy(function(s) { return s.length; }), javascript:alert(['hello', 'world', 'this', 'is', 'nice'].sortBy(function(s) { return s.length; }))
  116. 'background-color'.camelize(), javascript:alert('background-color'.camelize())
  117. 'background-color'.capitalize(), javascript:alert('background-color'.capitalize())
  118. 'We demand rigidly defined areas of doubt and uncertainty', javascript:alert('We demand rigidly defined areas of doubt and uncertainty'.gsub(/[ei]/, function(match){if (match[0] == 'e') return 3; return 1;}))
  119. 'On the way back, they sang a number of tuneful and reflective songs on, javascript:alert( 'On the way back, they sang a number of tuneful and reflective songs on the subjects of peace, justice, morality, culture, sport, family life, and the obliteration of all other life forms.'.truncate(16, suffix ='...'))
  120. myTemplate.evaluate(show), javascript:alert(myTemplate.evaluate(show))

This talk available at http://jmvidal.cse.sc.edu/talks/ajax/
Copyright © 2009 José M. Vidal . All rights reserved.

20 February 2008, 01:43PM