Skip to content

banner ajax
The Complete Reference: Ajax

AjaxTCR Library Source

  • AjaxTCR Library
/*
 * AjaxTCR Library
 * Software License Agreement (BSD License)
 *
 * Copyright © 2007, Pint, Inc.
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 *   - Redistributions of source code must retain the above
 *      copyright notice, this list of conditions and the following
 *      disclaimer.
 * 
 *   - Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the
 *      following disclaimer in the documentation and/or other materials
 *      provided with the distribution.
 *
 *   - Neither the name of Pint Inc. nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission of Pint Inc.
 *
 *
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Docs are generated using java -jar app/js.jar app/run.js -t=templates/htm -d=../docs ../ajaxtcr.js
 * OR for private included: java -jar app/js.jar app/run.js -p -t=templates/htm -d=../docsall ../ajaxtcr.js
 */

/**
 * @fileOverview 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. 
 * @name ajaxtcr.js
 */

/**
* The AjaxTCR global namespace object.  
* @class AjaxTCR
* @static
*/

var AjaxTCR = {};

/**
 * The communication class of the library.  Contains communication methods
 * as well as subclasses for caching, queueing, collecting statistics, and accessing 
 * cookies
 * @class AjaxTCR.comm
 * @static
 */

AjaxTCR.comm = {
    
/******************************************  Constants  ******************************************/

/** readyState constants as defined by w3c */

 UNSENT : 0,
 OPEN :   1,
 SENT : 2,
 LOADING : 3,
 DONE : 4,


/** Default HTTP request method 
 * @private
 */
DEFAULT_REQUEST_METHOD : "GET",

/** Default async option 
 * @private
 */
DEFAULT_ASYNC : true,


/** Default option to prevent browser caching of request.  
 * Only  works with XHRs and is done by setting the "If-Modified-Since" header 
 * @private
 */
DEFAULT_PREVENT_CACHE: false,
  
/** Default Request Content Type  
 * @private
 */
DEFAULT_CONTENT_TYPE : "application/x-www-form-urlencoded",


/** Default Request Content Transfer Encoding  
 * @private
 */
DEFAULT_CONTENT_TRANSFER_ENCODING : "",

/** Default indicate transport scheme used.  If set will include the transport scheme in the headers or payload  
 * @private
 */
DEFAULT_TRANSPORT_INDICATOR : true,


/** Default timeout in ms.   
 * @private
 */
DEFAULT_TIMEOUT : 0,

/** Default number of Retries  
 * @private
 */
DEFAULT_RETRIES : 0,
 

/** Default show progress  
 * @private
 */
DEFAULT_SHOW_PROGRESS : false,

/** Default time to revisit our progress callback if monitoring progress  
 * @private
 */
DEFAULT_PROGRESS_INTERVAL : 1000,


/** Default enforce order.  If set, it will enforce order on all requests that have the value set, but not those without  
 * @private
 */
DEFAULT_ENFORCE_ORDER : false,

/** Default Cache Response  
 * @private
 */
DEFAULT_CACHE_RESPONSE : false,


/** Default to put the responseText into outputTarget  
 * @private
 */
DEFAULT_USE_RAW : true,

/** Default one way transmission.  Will not call any callbacks if set 
 * @private
 */
DEFAULT_ONEWAY : false,


/** Default signature to use to sign request.  Places value in the header  
 * @private
 */
DEFAULT_REQUEST_SIGNATURE : "X-Signature",

/** Default option if the response is signed  
 * @private
 */
DEFAULT_SIGNED_RESPONSE : false,


/** Default transport scheme  
 * @private
 */
DEFAULT_TRANSPORT : "xhr",

/** Default transport string value.  Name of the header or payload value that will be sent with request  
 * @private
 */ 
DEFAULT_TRANSPORT_HEADER : "X-Requested-By",


/** Default values to set the transport value to. 
 * @private
 */
DEFAULT_XHR_TRANSPORT_VALUE: "XHR",
DEFAULT_IFRAME_TRANSPORT_VALUE: "iframe",
DEFAULT_IMAGE_TRANSPORT_VALUE: "image",
DEFAULT_SCRIPT_TRANSPORT_VALUE: "HTMLScriptTag",


/** Fallback to another transport if XHR fails  
 * @private
 */
DEFAULT_FALLBACK : true,

/** Default fallback transport scheme  
 * @private
 */
DEFAULT_FALLBACK_TRANSPORT: "iframe",


/** Default output handing.  Places responseText into outputTarget with this method  
 * @private
 */
DEFAULT_INSERTION_METHOD : "replace",

/** Cache the template  
 * @private
 */
DEFAULT_CACHE_TEMPLATE : true,


/** Default location for rendering templates  
 * @private
 */
DEFAULT_TEMPLATE_RENDER : "client",

/** Constant for server defined template file  
 * @private
 */
TEMPLATE_SERVER_DEFINED : "dynamic",



/****************************************** Private Properties ****************************************************/
 
/** the request id counter  
 * @private
 */    
 _requestID : 0,      

/** request counter shows outstanding requests  
 * @private
 */

_requestsOutstanding : 0,
 
/** the statuses for possible network errors
 *  3507 = library error flag 
 * @private
 */
 _networkErrorStatus : new Array(0, 408, 504, 3507, 12002, 12007, 12029, 12030, 12031, 12152),
 
 
 /*****************************************  GETTERS/SETTERS ***********************************/

/**
 * Updates a default value in the AjaxTCR.comm namespace.
 * 
 * @param {string} option The name of the option to update
 * @config {string} DEFAULT_REQUEST_METHOD Possible values - any valid HTTP Method.  Default: "GET"
 * @config {boolean} DEFAULT_ASYNC Default: true 
 * @config {boolean}DEFAULT_PREVENT_CACHE Default: false,
 * @config {string} DEFAULT_CONTENT_TYPE Default : "application/x-www-form-urlencoded",
 * @config {string} DEFAULT_CONTENT_TRANSFER_ENCODING Default : "",
 * @config {boolean}DEFAULT_TRANSPORT_INDICATOR Default : true,
 * @config {integer} DEFAULT_TIMEOUT Default : 0,
 * @config {integer} DEFAULT_RETRIES Default : 0,
 * @config {boolean} DEFAULT_SHOW_PROGRESS Default : false,
 * @config {integer} DEFAULT_PROGRESS_INTERVAL Default : 1000,
 * @config {boolean} DEFAULT_ENFORCE_ORDER Default : false,
 * @config {boolean} DEFAULT_CACHE_RESPONSE Default : false,
 * @config {boolean} DEFAULT_USE_RAW Default : true,
 * @config {boolean} DEFAULT_ONEWAY Default : false,
 * @config {string} DEFAULT_REQUEST_SIGNATURE Default : "X-Signature",
 * @config {boolean} DEFAULT_SIGNED_RESPONSE Default : false,
 * @config {string} DEFAULT_TRANSPORT Default : "xhr",
 * @config {string} DEFAULT_TRANSPORT_HEADER Default : "X-Requested-By",
 * @config {string} DEFAULT_XHR_TRANSPORT_VALUE Default : "XHR",
 * @config {string} DEFAULT_IFRAME_TRANSPORT_VALUE Default : "iframe",
 * @config {string} DEFAULT_IMAGE_TRANSPORT_VALUE Default : "image",
 * @config {string} DEFAULT_SCRIPT_TRANSPORT_VALUE Default : "HTMLScriptTag",
 * @config {boolean} DEFAULT_FALLBACK Default : true,
 * @config {string} DEFAULT_FALLBACK_TRANSPORT Default : "iframe",
 * @config {string} DEFAULT_INSERTION_METHOD Default : "replace",
 * @config {boolean} DEFAULT_CACHE_TEMPLATE Default : true,
 * @config {string} DEFAULT_TEMPLATE_RENDER Default : "client",
 * @config {string} TEMPLATE_SERVER_DEFINED Default : "dynamic",
 * @param {object} value  The value to set the option to.
 */                                

setDefault : function(option, value){
    AjaxTCR.comm[option] = value;

},

/**
 * Retrieves the default value in the AjaxTCR.comm namespace for the given option
 * 
 * @param {string} option The name of the option to fetch
 * @return {string} The value of the passed in option
 */
getDefault : function(option){
    return AjaxTCR.comm[option]

},                


/******************************************  Public Methods  ******************************************/

/**
 * sendRequest - public method to create an Ajax style request
 * 
 * @param url     string of URL to send request to
 * @param options  object containing the options for the request
 * @config {Boolean} async    Defines if the request should be asynchronous or not.  The default is true when not specified.
 * @config {string} 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
 * @config {Boolean} cacheResponse    Boolean to indicate if the response should be saved in the response cache.    Default is false
 * @config {Boolean} 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
 * @config {string} 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
 * @config {Boolean} 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
 * @config {Boolean} 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
 * @config {string} 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"

 * @config {object} 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 []
 * @config {object} 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
 * @config {string} 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. <br />insertBefore put as element just before the specified element <br />insertAfter put as an element just after the specified element<br />firstChild put as the first child within the specified element<br />lastChild put as the last child within the specified element     <br />Default is "replace" 
 * @config {string} 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"

 * @config {function} onCreate    Called right after the XHR object is created.  Corresponds to readyState == 0.  Passes the request object.    Default is null
 * @config {Boolean} oneway    Indicates if the request is one way and thus if the response should be ignored.    Default is false
 * @config {function} 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 () {}
 * @config {function} 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
 * @config {function} onOpen    Callback that is called when the xhr.readyState == 1.  This occurs after xhr.open.  Passes the request object.    Default is null
 * @config {function} onPrefetch    Callback that is invoked when you are prefetching data but not yet using it.    Default is function (){} 
 * @config {function} 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 () {}
 * @config {function} 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
 * @config {function} onRetry    Callback function that is called when retry is enabled.  Called very time a retry occurs.    Default is function () {}
 * @config {function} onSent    Callback that is called when the xhr.readyState = 2.  This occurs right after xhr.send().  Passes the request object.    Default is null
 * @config {function} 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
 * @config {function} 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 () {}
 * @config {function} 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 () {}
 * @config {object} 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
 * @config {string} password    The password to be used when addressing HTTP authentication challenges.  Only supported with the XHR transport.     Default is ""
 * @config {string} 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 AjaxTCR.data 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 ""
 * @config {Boolean} 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
 * @config {millisecond} progressInterval    This value is used to indicate how often the request should be polled for progress updates in milliseconds.  Defaults to 1 second (1000ms).
 * @config {string} 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"
 * @config {string} requestContentTransferEncoding encodingType    Sets the Content-Transfer-Encoding header on the request to the defined value.    Default is ""
 * @config {string} requestSignature    Indicates the header used when signing requests and will contain the contents of signRequest property if it is set.    Default is "X-Signature"

 * @config {integer} 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
 * @config {object} 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
 * @config {Boolean} showProgress    Setting this property to true indicates that the progress event will fire.    Default is false
 * @config {string} 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
 * @config {Boolean} 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
 * @config {object} 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
 * @config {string} 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
 * @config {string} 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"

 * @config {number} 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
 * @config {string} 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"

 * @config {Boolean} 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
 * @config {Boolean} 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
 * @config {string} username    Used to specify the username for HTTP authentication challenges issued to a request.  Only usable with an XHR transport.    Default is ""
 * @config {Boolean} 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
 * @config {object} userVars    Value attached to the request/response object that may contain any form of user defined data.    Default is undefined
 * @return {object} The newly generated request object.
 */    
 sendRequest : function (url,options) {

     
    var request = new Object();
        
    /* increment our requestId number */  
    request.requestID = ++AjaxTCR.comm._requestID;
    
    /* basic communication defaults */

    request.method = AjaxTCR.comm.DEFAULT_REQUEST_METHOD;
    request.async = AjaxTCR.comm.DEFAULT_ASYNC;
    request.preventCache = AjaxTCR.comm.DEFAULT_PREVENT_CACHE;
    request.requestContentType = AjaxTCR.comm.DEFAULT_CONTENT_TYPE;
    request.requestContentTransferEncoding = AjaxTCR.comm.DEFAULT_CONTENT_TRANSFER_ENCODING;
    request.payload = "";

    /* header management */

    request.headers = new Array();
    request.transportIndicator = AjaxTCR.comm.DEFAULT_TRANSPORT_INDICATOR;

    /* standard callbacks */

    request.onSuccess = function(){};
    request.onFail = function(){};
    
    /* callbacks associated with readyState changes */

    request.onCreate = null;
    request.onOpen = null;
    request.onSent = null;
    request.onLoading = null;
    request.onReceived = null;

    /* communication status flags */    
    request.abort = false;
    request.inProgress = true;
    request.received = false;
    
    /* progress management */

    request.showProgress = AjaxTCR.comm.DEFAULT_SHOW_PROGRESS;
    request.progressInterval = AjaxTCR.comm.DEFAULT_PROGRESS_INTERVAL;
    request.onProgress = function (){};
    request.progressTimerID = null;
    
    /* timeout parameters */

    request.timespent = 0;
    request.timeout = AjaxTCR.comm.DEFAULT_TIMEOUT;
    request.onTimeout = function(){};
    request.timeoutTimerID = null;

    /*  retry parameters */

    request.retries = AjaxTCR.comm.DEFAULT_RETRIES;
    request.retryCount = 1;
    request.onRetry = function (){};
    
    /* sequencing */

    request.inQueue = false;
    request.responseQueueID = 0;
    request.enforceOrder = AjaxTCR.comm.DEFAULT_ENFORCE_ORDER;

    /* cache management */

    request.cacheResponse = AjaxTCR.comm.DEFAULT_CACHE_RESPONSE;
    request.fromCache = false;
    
    /* Prefetch */

    request.onPrefetch = function(){};
    request.isPrefetch = false;

    /* payload serialization */

    request.serializeForm = null;
    request.hasFile = false;

    /* output handling */

    request.outputTarget = null;
    request.useRaw = AjaxTCR.comm.DEFAULT_USE_RAW;
    request.insertionType = AjaxTCR.comm.DEFAULT_INSERTION_METHOD;
    
    /* transmission type */

    request.oneway = AjaxTCR.comm.DEFAULT_ONEWAY;
    
    /* authentication */

    request.username = null;
    request.password = null;
    
    /* security */

    request.requestSignature = AjaxTCR.comm.DEFAULT_REQUEST_SIGNATURE;
    request.signRequest = null;
    request.signedResponse = AjaxTCR.comm.DEFAULT_SIGNED_RESPONSE;

    /* history */

    request.history = null;
    
    /* transport/fallback */
    request.transport = AjaxTCR.comm.DEFAULT_TRANSPORT;
    request.fallback = AjaxTCR.comm.DEFAULT_FALLBACK;
    request.fallbackTransport = AjaxTCR.comm.DEFAULT_FALLBACK_TRANSPORT;
    request.cookieName = null;
    
    /* Templates */

    request.template = null;
    request.templateRender = AjaxTCR.comm.DEFAULT_TEMPLATE_RENDER;

    request.cacheTemplate = AjaxTCR.comm.DEFAULT_CACHE_TEMPLATE;
    request.shortTermCacheTemplate = false;
    
    request.statusIndicator = null;
    
    /* apply options defined by user */

    for (option in options)
      request[option] = options[option];
      
    if (request.isPrefetch)

        request.cacheResponse = true;
        
    /* Enable backguard if necessary */
    if (AjaxTCR.history._backGuardEnabled == AjaxTCR.history.BACK_GUARD_INITIALIZED)

        AjaxTCR.history._activateBackGuard();
        
    /* Check for/Fetch template */
    if (request.template && request.template != AjaxTCR.comm.TEMPLATE_SERVER_DEFINED && request.templateRender == "client")

    {
        if (!AjaxTCR.template.getFromCache(request.template))

        {
            request.enforceOrder = true;
            AjaxTCR.comm.sendRequest(request.template, {shortTermCacheTemplate:true, enforceOrder:true});
        }

    }
    else if (request.template && request.template != AjaxTCR.comm.TEMPLATE_SERVER_DEFINED && request.templateRender == "server")

    {
        if (request.payload != "")
            request.payload += "&";
        request.payload += "templateURL=" + request.template;
    }

      
    /* Serialize the given form if request.serialize is set */
    if (request.serializeForm)
    {

        /* Serialize given form */
        var newPayload = AjaxTCR.data.serializeForm(request.serializeForm,request.requestContentType);
        
        /* check to see if we have a fileupload situation */

        if (newPayload == "fileupload")
            request.hasFile = true;
        else

        {
            /* Check to see if payload exists */
            if (request.payload)

            {
                /* If payload is an object, use serializeObject otherwise append to end of the new payload */
                if (typeof(request.payload) == "object") 
                    newPayload = AjaxTCR.data.serializeObject(newPayload, request.payload, request.requestContentType);
                else if (request.requestContentType == AjaxTCR.comm.DEFAULT_CONTENT_TYPE)

                    newPayload += "&" + request.payload;  
            }
            
            request.payload = newPayload;
            
            /* Get all values into string format */

            if (request.requestContentType == "application/json")
                  request.payload = AjaxTCR.data.encodeJSON(request.payload);
            else if (request.requestContentType == "text/xml")

                request.payload = AjaxTCR.data.serializeXML(request.payload);
                
            /* Encode it in base64 if that's set */

            if (request.requestContentTransferEncoding == "base64")
                request.payload = AjaxTCR.data.encode64(request.payload);
        }

    }
    
    /* Add to history */
    if (request.history)

        AjaxTCR.history.init(function(){});
        
    if (request.history && !request.history.saveResponse)

        AjaxTCR.history.addToHistory(request.history.id, "", request.history.title, url,  options);
  
      /* If there is a file, we need to handle differently */

    if (request.hasFile)
        request.transport = "iframe";
    
    /* normalize the transport value */    
    request.transport = request.transport.toLowerCase();
    
    if (request.transport == "script" || request.transport == "image")

        request.method = "GET";
    
    if (request.method.toUpperCase() == "GET" && request.payload != "")

        request.url = url + "?" + request.payload;
    else

        request.url = url;
         
    if (request.method.toUpperCase() == "POST")

        request.postBody = request.payload;
    else
        request.postBody = null;
            
        
    /* Add a queueID if necessary */

    if (request.enforceOrder)
        request.responseQueueID = AjaxTCR.comm.queue._responseQueue.maxID++;
        
    var cachedResponse = null;
    /* Check if the item is in the cache first */

    if (request.cacheResponse)
    {
        /* Check to see if we have a key for our cache */

        if (request.cacheKey == undefined)
            request.cacheKey = request.url;
    
        cachedResponse = AjaxTCR.comm.cache.get(request.cacheKey);
        if (cachedResponse)

            AjaxTCR.comm.cache._handleCacheResponse(request, cachedResponse);
    }
        
    /* invoke the request */

    if (!cachedResponse)
        AjaxTCR.comm._makeRequest(request);
    

    /* return object for local control */

    return request;    
 },        
 
 
 /**
  * Public method that will abort any passed request object and clean up
  * any timers for showing requqest state
  * 
  * @param {object} request The request object generated through sendRequest.
  */
 abortRequest : function(request) {

          
    /* set the abort flag */
     request.abort = true;
                                     
    /* clear inProgress flag */

    request.inProgress = false;
                                     
    /* abort the request */    
    request.xhr.abort();
                                     
    /* decrement outstand request count */

    AjaxTCR.comm._requestsOutstanding--;
                                     
    /* clear any timeout timers */
    clearTimeout(request.timeoutTimerID);
    request.timeoutTimerID = null;
                                     
    /* stop showing progress */

    if (request.progressTimerID)
      {
       clearTimeout(request.progressTimerID);
       request.progressTimerID = null;
      }

                                        
    /* Remove Progress Indicators */
    if (request.statusIndicator)
      {

        AjaxTCR.comm._removeProgressStatus(request.statusIndicator);
      }                                    
},

/******************************************  Private Methods  ******************************************/

      
 
 /**
 * _createXHR - private method acting as a wrapper to make an XMLHttpRequest object.  Trys native
 *              object first and then ActiveX control.  Returns null if fails.
 * 
 * @private
 * @return {object} Either the native XHR Object or the most current ActiveX version supported.
 */    
 _createXHR : function() { 
                          
    try { return new XMLHttpRequest(); } catch(e) {}

    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}

    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}

    try { return new ActiveXObject("Msxml2.XMLHTTP"); }       catch (e) {}

    try { return new ActiveXObject("Microsoft.XMLHTTP"); }  catch (e) {}

                                         
    return null;
},

/**
 * Private method that decides which initializes the requesst, decides which transport to use, and calls the send method for that transport.
 * 
 * @private
 * @param {object} the Request Object to make the request with.
 */

_makeRequest : function (request) {        

                                    
    /* Increment total requests */

    AjaxTCR.comm.stats._commResults.totalRequests++;
                                    
    /* Display status and start Progress Callback */
    if (!request.oneway)

        AjaxTCR.comm._initSend(request);
                                  
    /* Call back for ready state 0 if set */
    if (request.onCreate)

      request.onCreate(request);
                                      
    if (request.transport == "xhr")

        AjaxTCR.comm._sendXHR(request);
    else if (request.transport == "iframe")

        AjaxTCR.comm._sendIframe(request);
    else if (request.transport == "script")

        AjaxTCR.comm._sendScript(request);
    else if (request.transport == "image")

        AjaxTCR.comm._sendImage(request);
                                                                           
},

/**
 * Private method that sends an XHR request.  It creates the XHR, fallsback if any problems are encountered, sets appropriate headers,
 * and sends the requesst.
 * 
 * @private
 * @param {Object} request The request that contains the options that we wish to send.
 * 
 */
                                 

_sendXHR : function(request){
    
    request.xhr = AjaxTCR.comm._createXHR();
    if (!request.xhr)

    {
        AjaxTCR.comm._fallbackOrError(request);
        return;
    }                                    
                            
    /* open the request */

    try{
        request.xhr.open(request.method, request.url, request.async, request.username, request.password);
    }

    catch(e){
        AjaxTCR.comm._fallbackOrError(request);
        return;
    }                                
    
    /* clear an abort flag in case this is a retry */

    request.abort = false;
                                    
    /* set headers indicating we did this with Ajax and what our transaction id is */
    if (request.transportIndicator)

    {
       request.xhr.setRequestHeader(AjaxTCR.comm.DEFAULT_TRANSPORT_HEADER,AjaxTCR.comm.DEFAULT_XHR_TRANSPORT_VALUE);
       request.xhr.setRequestHeader("X-Request-Id",request.requestID);
    }

                                      
    /* Set signature header */
    if (request.signRequest)
         request.xhr.setRequestHeader(request.requestSignature, request.signRequest);
                                
    /* set header(s) for POST */

    if (request.method.toUpperCase() == "POST")
    {

       request.xhr.setRequestHeader("Content-Type", request.requestContentType);
       if (request.requestContentTransferEncoding != "")

         request.xhr.setRequestHeader("Content-Transfer-Encoding", request.requestContentTransferEncoding);
    }
                                      
    /* Prevent Caching if set */

    if (request.preventCache)
        request.xhr.setRequestHeader("If-Modified-Since", "Wed, 15 Nov 1995 04:58:08 GMT");
                                      
    /* set user defined headers */

    request.headerObj = {};
    for (var i=0; i<request.headers.length;i++)

    {
        if (request.headers[i].name.toUpperCase() == "COOKIE")

            document.cookie = request.headers[i].value;
        else if(request.headerObj[request.headers[i].name] === undefined)

            request.headerObj[request.headers[i].name] = request.headers[i].value;
        else    
            request.headerObj[request.headers[i].name] =  request.headers[i].value + "," + request.headerObj[request.headers[i].name];
    }

                                    
    for (var header in request.headerObj)
        request.xhr.setRequestHeader(header, request.headerObj[header]);
                                    
    
    if (!request.oneway)

    {
        /* bind the success callback */
        request.xhr.onreadystatechange = function () {AjaxTCR.comm._handleReadyStateChange(request);};
                                    
        /* set a timeout if set */

        if (request.async && request.timeout && request.timeoutTimerID == null)

             request.timeoutTimerID = window.setTimeout( function(){AjaxTCR.comm._timeoutRequest(request);}, request.timeout);
        
    }

                                    
    /* send the request */
    request</