Library: ajaxtcr.js
The AjaxTCR library was built to support "Ajax: The Complete Reference". The primary purpose to cover all aspects of communications including XHR, fallback transports, request queue, response queue, caching, templates, many entries to callbacks, form serialization, and proper history management. The library also includes supporting functions for data manipulation, dom access, event handling, persistence, as well as caching, templates, and history outside of the scope of communications.
The AjaxTCR global namespace object.
The communication class of the library. Contains communication methods as well as subclasses for caching, queueing, collecting statistics, and accessing cookies
The caching class of the library. Is called directly from AjaxTCR.comm, but can also be called by the user.
  • add(key, val)
The queuing class of the library. Is called directly from AjaxTCR.comm.
  • add(url, options, priority)
The statistics class of the library. Collects statistics regarding total requests, timeouts, retries, successes, and failures Can serialize and send this data to your server.
The cookie class of the library. Allows setting and retrieving of cookies
  • set(key, value, expires, path)
The history class of the library. History is called directly from communications, but can also be called by the user. If history is going to be used, you must call AjaxTCR.history.init() before usage.
  • init(onStateChangeCallback, initState)
The storage class of the library. Storage is called directly from history, but can also be called by the user. If storage is going to be used, you must call before usage. The types of storage supported are IE Behaviors, WHATWG globalStorage, and cookies
  • add(key, value, persistObj, store)
  • get(key, persistObj, store)
  • clear(persistObj, store)
  • remove(key, persistObj, store)
The template class of the library. Is called directly from AjaxTCR.comm, but can also be called by the user.
Several useful data functions. encode/decode/serialize for several different data formats. Many of these are called from other parts of the library.
While the main purpose of the library is communication functions, it was necessary to add in some utility methods. The AjaxTCR.util holds these methods.
Several useful utility DOM functions. Many of these are called from other parts of the library.
The library doesn't currently offer large event handling support, but some basics are included in this calss
The place for anything that doesn't have a home
AjaxTCR.comm.setDefault(option, value)
Updates a default value in the AjaxTCR.comm namespace.
string option The name of the option to update
string option.DEFAULT_REQUEST_METHOD Possible values - any valid HTTP Method. Default: "GET"
boolean option.DEFAULT_ASYNC Default: true
boolean option.DEFAULT_PREVENT_CACHE Default: false,
string option.DEFAULT_CONTENT_TYPE Default : "application/x-www-form-urlencoded",
boolean option.DEFAULT_TRANSPORT_INDICATOR Default : true,
integer option.DEFAULT_TIMEOUT Default : 0,
integer option.DEFAULT_RETRIES Default : 0,
boolean option.DEFAULT_SHOW_PROGRESS Default : false,
integer option.DEFAULT_PROGRESS_INTERVAL Default : 1000,
boolean option.DEFAULT_ENFORCE_ORDER Default : false,
boolean option.DEFAULT_CACHE_RESPONSE Default : false,
boolean option.DEFAULT_USE_RAW Default : true,
boolean option.DEFAULT_ONEWAY Default : false,
string option.DEFAULT_REQUEST_SIGNATURE Default : "X-Signature",
boolean option.DEFAULT_SIGNED_RESPONSE Default : false,
string option.DEFAULT_TRANSPORT Default : "xhr",
string option.DEFAULT_TRANSPORT_HEADER Default : "X-Requested-By",
string option.DEFAULT_XHR_TRANSPORT_VALUE Default : "XHR",
string option.DEFAULT_IFRAME_TRANSPORT_VALUE Default : "iframe",
string option.DEFAULT_IMAGE_TRANSPORT_VALUE Default : "image",
string option.DEFAULT_SCRIPT_TRANSPORT_VALUE Default : "HTMLScriptTag",
boolean option.DEFAULT_FALLBACK Default : true,
string option.DEFAULT_FALLBACK_TRANSPORT Default : "iframe",
string option.DEFAULT_INSERTION_METHOD Default : "replace",
boolean option.DEFAULT_CACHE_TEMPLATE Default : true,
string option.DEFAULT_TEMPLATE_RENDER Default : "client",
string option.TEMPLATE_SERVER_DEFINED Default : "dynamic",
object value The value to set the option to.
Retrieves the default value in the AjaxTCR.comm namespace for the given option
string option The name of the option to fetch
string The value of the passed in option
AjaxTCR.comm.sendRequest(url, options)
sendRequest - public method to create an Ajax style request
url string of URL to send request to
options object containing the options for the request
Boolean options.async Defines if the request should be asynchronous or not. The default is true when not specified.
string options.cacheKey By default, when cache is turned on, items are saved in cache using the URL of the object as a key. If another value is desired you may set it through this property though you will be responsible for manually retrieving as the request system will use the URL of requests to determine if something is cached or not. Default is URL of request
Boolean options.cacheResponse Boolean to indicate if the response should be saved in the response cache. Default is false
Boolean options.cacheTemplate Indicates that if a cache is returned with the response if it should be saved in the template cache or not. Default is true
string options.cookieName The name of the cookie expected upon response when the transport type is image. If specified the responseText will be populated with the value of this cookie only. If unspecified responseText will contain the entire cookie and the developer is required to parse out the response manually. Should be set if outputTarget is also specified with request. Default is document.cookie
Boolean options.enforceOrder Boolean to force every response that has this value set to be returned in the order in which it was sent, this means that requests may be held until previous requests arrive. Default is false
Boolean options.fallback Defines if the communication mechanism should fallback to another method if the XHR fails for some reason. The fallback transport scheme is defined by fallbackTransport or the global default is consulted. Default is true
string options.fallbackTransport Options are "iframe" | "script" | "image" Defines the particular communication mechanism that should be used if XHRs fail for some reason fallback. If undefined the global default (iframe) is used unless it has been overridden. . Default is "iframe"
object options.headers Array-of-Header Objects An array of header objects to be sent with the request. The header object must have two properties called name and value with the appropriate values. It is set up in this manner to allow multiple values for a single name. The library will append these together with ‘,’. Note that setting a Cookie header should be avoided particularly if more than one value is set and document.cookie should be used instead. Default is []
object options.history Used to control the history mechanism on a request basis. The passed object has three properties, saveResponse, id, and title. The saveResponse property indicates that the response will be cached and when a user backs up to the page in question another request will not be issued. By default responses will not be saved. The id is the value used in the hash mark (ex. #currentState), the id is required. The title property is used to set the title of the page so as to reflect the current state of the application. Default is null
string options.insertionType "insertBefore" | "insertAfter" | "firstChild" | "lastChild" | "replace" Used in conjunction with outputTarget to define how content returned should be handled relative to the element specified by the outputTarget value. By default the returned content will replace the outputTarget element content. Other values include.
insertBefore put as element just before the specified element
insertAfter put as an element just after the specified element
firstChild put as the first child within the specified element
lastChild put as the last child within the specified element
Default is "replace"
string options.method HTTP-method Sets the method for the request to the string HTTP-method. No limit to what is settable, though some XHR implementations will not support some methods and of course destinations may reject methods. If unset a default method will be used. Note that some browsers XHR implementations will not allow for extended HTTP methods and that alternate transfers may be even more restrictive (iframe - GET and POST, all other transports - GET only) Default is "GET"
function options.onCreate Called right after the XHR object is created. Corresponds to readyState == 0. Passes the request object. Default is null
Boolean options.oneway Indicates if the request is one way and thus if the response should be ignored. Default is false
function options.onFail Callback that is called when a server error occurs. Most often this occurs when the status != 200. Passes the request object along with a message describing the error. Default is function () {}
function options.onLoading Callback that is called with the xhr.readyState == 3. This occurs when the data begins to come back. Passes the request object. Default is null
function options.onOpen Callback that is called when the xhr.readyState == 1. This occurs after Passes the request object. Default is null
function options.onPrefetch Callback that is invoked when you are prefetching data but not yet using it. Default is function (){}
function options.onProgress Callback invoked by default once every second. Useful for updating the user to the progress of long requests. Often used with the status object. You can override the default progressInterval of one second if desired. Default is function () {}
function options.onReceived Callback that corresponds to readyState 4 but without having looked at the success or failure of the request yet, thus it will be called before onSuccess or onFail. Default is null
function options.onRetry Callback function that is called when retry is enabled. Called very time a retry occurs. Default is function () {}
function options.onSent Callback that is called when the xhr.readyState = 2. This occurs right after xhr.send(). Passes the request object. Default is null
function options.onStatus Callback that is invoked for the corresponding status code. For example the callback for on404 is called when a response of 404 is received while an on500 is called when a 500 response code is received. Default is undefined
function options.onSuccess Primary callback that will be called whenever the request completes successfully with a status of 200. Passes the response object as a parameter. Default is function () {}
function options.onTimeout Callback that is invoked when a timeout occurs. If there are retries and continual failures this callback may be invoked numerous times. Default is function () {}
object options.outputTarget When specified the request’s responseText will be automatically inserted into the specified object using its innerHTML property. The object should be a reference to a DOM element or a string to be used that references an existing DOM element by its id attribute. The useRaw option can be set to false so that a user may desire to override the immediate placement of content but still use this property as a reference. Default is null
string options.password The password to be used when addressing HTTP authentication challenges. Only supported with the XHR transport. Default is ""
string options.payload The payload is a properly encoded string (or object) to be submitted in a query string or message body depending on the HTTP method used. Various methods like encodeValue() and serializeForm() may be used to quickly form a payload. The payload must be in the format in which it is going to be used. Default is ""
Boolean options.preventCache When set to true, attempts to disable caching by setting the request header to a very old date. Users may also desire to add a unique query string as well. Default is false
millisecond options.progressInterval This value is used to indicate how often the request should be polled for progress updates in milliseconds. Defaults to 1 second (1000ms).
string options.requestContentType MimeType string The content type on the request. If the request is a POST, it will set the request Content-Type header to this value. Will base form serialization on it as well. Default is "application/x-www-form-urlencoded"
string options.requestContentTransferEncoding encodingType Sets the Content-Transfer-Encoding header on the request to the defined value. Default is ""
string options.requestSignature Indicates the header used when signing requests and will contain the contents of signRequest property if it is set. Default is "X-Signature"
integer options.retries Indicates if a request should be retried if an error is encountered or a timeout occurs. Set to false or 0 to not retry failed requests. Set this value larger than 0 to indicate number of retries Default is 0
object options.serializeForm Automatically encodes the contents of the form specified as an object, id or name. A default encoding of x-www-form-urlencoded will be used unless the requestContentType attribute is set. Default is null
Boolean options.showProgress Setting this property to true indicates that the progress event will fire. Default is false
string options.signRequest "signature string" Used to sign a request, typically it is an MD5 hash value that will be put in the Web page when generated by a server-side program. Default is null
Boolean options.signedResponse If the response is signed, the library will check the "Content-MD5" header in the response and compare it to a MD5 encoding of the responseText. If they do not match, onFail is called and the responseText is not returned. Default is false
object options.statusIndicator statusObject The property should be set to an object which contains visual display information for indicating status. At this point it supports an object with a single property progress set to an object containing type which can be either image or text, imageSrc which is the URL of the image to use in the case type is set to image, and text is a string to use in the case the type is set to text. A target property is set to the DOM id reference of the place the status should be displayed. Default is null
string options.template URL | "dynamic" If a URL is specified the template to apply to a response will be fetched. If the string value of “dynamic” is used a server-side program will respond and include a template value either as a string or as URL to fetch. These values are found in the response packet in JSON format at the properties templateText and templateURL respectively. Default is null
string options.templateRender "client" | "server" String indicating if a template should be rendered on client or server, only works if the template property is set. A default value of client is assumed when template is set but templateRender is not. Default is "client"
number options.timeout Indicates whether to timeout or not. False or 0 indicates not to catch timeouts. A number greater than 0 indicates the number of milliseconds before timing out. Default is false
string options.transport "xhr" | "iframe" | "script" | "image" Transport to make the request with. By default this will be XHR though you can change it on a per request basis. The global transport can be set with setDefault("transport",value) where value one of the defined strings. The transport choice may change a request depending on the capabilities of the transport indicated. For example, image and script transports will not accept a POST request and will convert it into a GET if possible. Default is "xhr"
Boolean options.transportIndicator Indicates if Ajax indicating headers such as X-Requested-By: XHR should be included. Normally defined by value AjaxTCR.comm.DEFAULT_TRANSPORT_INDICATOR. Setting as an option effects only the request made, use the general the getter/setter AjaxTCR.comm.setDefault("DEFAULT_TRANSPORT_INDICATOR", false); Default is true
Boolean options.useRaw By default this is set to true and is consulted when outputTarget is set. If set to false the response’s payload will not be directly put into the outputTarget forcing you to manually perform any decode and placement. Default is true
string options.username Used to specify the username for HTTP authentication challenges issued to a request. Only usable with an XHR transport. Default is ""
Boolean options.useRaw This value is consulted when outputTarget is set. If set to false the response’s payload will not be directly put into the outputTarget forcing you to manually perform any decode and placement. Default is true
object options.userVars Value attached to the request/response object that may contain any form of user defined data. Default is undefined
object The newly generated request object.
Public method that will abort any passed request object and clean up any timers for showing requqest state
object request The request object generated through sendRequest.
AjaxTCR.comm.cache.add(key, val)
Adds a key/value pair to the cache. Removes any itmes first if necessary.
string key The key to reference the stored object
object val The value to save
Public method that resets the caches
Public method to fetch an object based on the key. Checks to see if the object has expired before returning it.
string key The key to reference the stored object
object The stored value
Returns the entire cache
object The cache Object
Returns the number of items currently in the cache
integer The number of items in the cache
Removes an item from the cache based on the key passed in
string key The key to reference the item to remove.
Changes the default options for the caching mechanism
Object the options to set
integer the.size The number of items to store in the cache Default is 100
string the.algorithm The algorithm to use to decide which item should be removed next. Options are LRU (Least Recently Used), FIFO (First In First Out), and LFU(Least Frequently Used) Default is LRU
integer the.expires The number of minutes an item can stay in the cache. Default is 60. Use -1 to set forever.
AjaxTCR.comm.queue.add(url, options, priority)
Public method to add a request to the request queue. If the request limit isn't being met yet, the request is sent right away, otherwise, it gets added to the queue. If the priority is set and not to "normal", it places the new request at the proper place. Otherwise, it inserts it at the end of the queue.
string url - the url to add to the request queue
object options - the options object to send to sendRequest
string priority? - the priority level of the entry - Choices are "normal", "next", and "faster"
integer The requestQueueid of the request
A public method that clears out the request queue of any pending requests
Returns the item from the queue
integer ID - ID of request to return
object The object that is stored in the queue
Returns the whole request queue
object the request queue
Returns the position in the queue of the passed in ID.
ID - ID of request that you wish to check
integer Returns -1 if not in queue. Otherwise returns th location in the queue. Starts at 0.
Returns the length request queue
integer the request queue length
Removes the option with the given requestQueueID from the request Queue
{integer{ ID ID of request to be removed from queue
Private method called after response comes in if request is in the response queue. Adds response to response queue and then calls callbacks for any that are able to move forward
object response The object that contains all the settings for the request
Sets up system to send results to the passed in URL on page unload. It passes them as a POST with an application/json body.
Object url URL to send the results to
Returns the whole statistics object
object the statistics object
Public method acting as simple getter for the count of requests currently out
string type The type of requests that you want the count on. Options are "queued", "active", and "all"
- the number of outstanding requests
Gets the value of a cookie with the given name.
String name The name of the cookie to find
String The value of the specified cookie
AjaxTCR.comm.cookie.set(key, value, expires, path)
Create a cookie using document.cookie
string key The cookie name
string value The cookie value
string expires The date of expiration. If not set, the cookie expires when the browser is closed.
string path? The path to store the cookie. If not set, it is stored at "/"
AjaxTCR.comm.cookie.remove(key, path)
Removes the cookie specified by key.
Object key The name of the cookie to remove
Object path? The path where the cookie is stored. If not set, it checks "/"
AjaxTCR.history.init(onStateChangeCallback, initState)
Function that must be called before using the history mechanics. It sets historyEnabled to true, sets the callback function, sets up the timers to check for history change and checks to see if the initial state is a bookmark
function onStateChangeCallback The function to call if there is a state change outside of the XHR call
Object initState The data to pass back to the callback function
AjaxTCR.history.addToHistory(id, data, title, url, options)
Adds an item to the browser history. Saves the title, position in history, and the data for later retrieval.
string id the key to store the history item under
object data the data field to be returned to the callback function.
title title? the title to change the page to
string url? the url to request when page reloads.
object options? the options for the request
Returns the entire history array
array The history array
Returns the current position in the history stack
integer The current position in the history stack
AjaxTCR.history.enableBackGuard(message, immediate)
Sets up the system that will alert the user when they leave the page that they are leaving the application
string message? The message to alert the user
Boolean immediate? If set to true, it immediately sets up the system. Otherwise, it sets it up on first sendRequest call.
Method must be called before using storage. The returned value must be passed to all future storage requests
object The newly created persitent Div object, value, persistObj, store)
Adds an item to storage. Checks the browser support and chooses an appropriate method.
String key The key to reference the stored string
String value The string to store in persistent data
Object persistObj The persistent Object returned from init
string store? Optional value to name the store to save the data. Only applicable in IE, persistObj, store)
Retrives the saved value from persisted data.
String key The key of the value to retrieve
Object persistObj The persistent Object returned from init
String store? Optional value to name the store to save the data. Only applicable in IE, store)
Returns all items from the storage in an associative array of name/value pairs
Object persistObj The persistent Object returned from init
String store? Optional value to name the store to save the data. Only applicable in IE, store)
Removes all items from persistent storage.
Object persistObj The persistent Object returned from init
String store? Optional value to name the store to save the data. Only applicable in IE, persistObj, store)
Remove the given item from persistent storage.
string key The name of the item to remove from storage
Object persistObj The persistent Object returned from init
String store? Optional value to name the store to save the data. Only applicable in IE
AjaxTCR.template.translateString(template, data)
Method that takes a template and a JSON object and converts into output
string template template string.
JSON string data a JSON string to be used in rendering template
string String formatted by template and populated with data from data
AjaxTCR.template.translateFile(template, data, cache)
Method that takes a template filename and a JSON object, fetches the file, and converts into output
string template template filename.
string data a JSON string to be used in rendering template
boolean cache a boolean indicating whether to cache the response or not
string output string formatted by given template file and polulated with data from data.
AjaxTCR.template.addToCache(key, val)
Method that caches a template file usually the URL of the template file is used as the key and template as the value.
string key key to add to the template cache
string val value to store in the template cache
AjaxTCR.template.cache(key, val)
Adds a url and optional value string to the template cache. If the value is set, it simply calls addToCache. If value is not set, it requests the file at the given URL and caches the results
string key key to add to the template cache
string val value to store in the template cache
Fetches a page that contains a template bundle. The expected response is in this format: <!-- Template-Begin URL='rating-Ajax.tpl' -->
<h3>Thanks for voting!</h3>
<p>Your rating: {$userrating}. <br />
Average rating: {$avgrating}.<br />
Total votes: {$totalvotes}. <br />
<!-- Template-End -->
<!-- Template-Begin URL='thankyou-Ajax.tpl' -->
<h2>Thank you for registering {$username}</h2>
<p>Contact technical support at 555-1212</p>
<!-- Template-End -->
url - URL of the template bundle to fetch
Public method that resets the template's cache
public method to fetch a cached template based on the key
string key key to add to the template cache
string the cached object value if found
public method to remove an item from the template cache based on the key
string key key of item to remove from template cache
Public method to encode passed string values to make the URL safe. Strictly encodes to x-www-urlencoded format vs. native methods found in JavaScript.
string val - the value to encode
string a string that is properly x-www-urlencoded as a browser would do it
Public method to decode passed string values from a URL safe string.
string val - the value to decode
string a string that is properly reversed from the proper x-www-urlencoded format
Public method to convert tag characters to < and > and change \n to
string str String to modify
string The str value with the conversions in place
Public method to encode passed string values into base64.
string inputStr A string value to encode
string The inputStr value encoded in base64
Public method to decode passed string values from base64.
string inputStr A string in base64 format
string The decoded string, encoding, trigger, evt)
Public method to create a serialized payload based on the contents of a form and the specified encoding value. trigger and evt are optional and used to firm up the accuracy between what the browser would send and what we send.
object form The form to be serialized
string encoding The encoding of the result. Options are "application/json", "application/x-www-form-urlencoded", "text/plain", "text/xml"
object trigger The element that caused the submission of the form. input type="button" fields will only be included in the payload if they triggered the submission.
object evt In the case that a input type="image" caused the submission, if the evt is passed in, the coordinates of the click will be put in the payload
string The payload serialized according to the specified encoding., obj, encoding)
Public method to create/modify a serialized object based on an object
object payload the current object that will be appended to.
object obj is the object to add to the payload
string encoding The encoding of the result. Options are "application/json", "application/x-www-form-urlencoded", "text/plain", "text/xml"
object The new payload with the object included
Returns the string version of the given XML Object
object xmlObject The xml object
string The xmlObject in string form
Returns the XML Object of the given string
string xmlStr A string that can be converted to XML
object The xmlObject generated from the string
Convert JSON into JavaScript values
string jsonString A string that can be converted to JavaScript arrays and objects
object A javascript object generated from the passed in string.
Turn JavaScript values into a JSON String
object o A object to be converted into a JSON string
string A string representation of the passed in object
encodeMD5(string) public method to get md5 encode a string Based on Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet Distributed under the BSD License See for more info.
string str The string to encode
string A string that is encoded in MD5 format
AjaxTCR.util.DOM.getElementsByClassName(classToFind, startNode)
Find elements by class, will be overriden by native if found If startNode is specified, starts the search there, otherwise starts at document.
string classToFind the string class name to search for
object startNode the DOM node to start the search at. Default is the document node.
array array of elements that match the given class name.
AjaxTCR.util.DOM.getElementsById(element, startNode)
Returns element or element array specified by given string or strings.
object element
object startNode the DOM node to start the search at. Default is the document node.
object if single string, it returns the element. Otherwise it returns an array of elements
AjaxTCR.util.DOM.getElementById(id, startNode, deepSearch)
Modified version of getElementById to return single node match. If startNode is not set to document, it starts the search at the node If deepSearch is set to true, it does not use getElementById, but instead loops through the whole structure.
string id the string to match with the id attribute
object startNode the DOM node to start searching in the document
boolean deepSearch true if wanted to search node by node instead of document.getElementById
AjaxTCR.util.DOM.getElementsBySelector(selector, treeRoot)
Select nodes that match the given selector. The selector is expected to be in CSS format
string selector string indicating the selection to match
object treeRoot DOM element to start search. Default is the document node
array of matching elements
AjaxTCR.util.DOM.insertAfter(parent, obj, sibling)
Inserts the passed object after the sibling with the given pareny
Object parent The parent of the node to insert
Object obj The new node to insert
Object sibling The sibling to insert after
addWindowLoadEvent - simple method to allow for safe addition of window.onload called functions. Assumes everyone else plays nicely though.
object newFunction - function to call upon page load
generateUID : Generates a unique value. If 'prefix' is set to -1, only returns the numerical value. If prefix isn't set, it sets it to "AjaxTCR".
string prefix? the string value to prepend to the uniquevalue
the string consisting of the prefix and the uniquevalue
readyState constants as defined by w3c
The number of active requests to send out when using request Queue
The max size to store in cookies
by default enable shorthanding of function names
Generated by JsDoc Toolkit 1.3.0 on Fri, 14 Sep 2007 18:35:45 GMT