ajax.js

Summary

AjaxRequest is a JavaScript class designed to make dealing with XMLHttpRequests (or the IE versions thereof) simplier. Example usage:

 <input type="text" name="foo" onchange="update();"/>
 ....
 function update() {
  	var req = new AjaxRequest();
	req.get(
		{ 
		'url'		: "/ajax/update.action",
		'onSuccess'	: updateCallback,
		'onLoading'	: function () { throbber(true); },
		'onDone' 	: function() { setTimeout('throbber(false);',250); }
		});
 }

 function updateCallback(req) { // This is the required signature for a callback
	if (req.responseXML) {
 		// process xml file in javascript
	}
 }
 


Version: 0.2

Author: Marcus R. Breese


Class Summary
AjaxRequest  

/**
 * @fileoverview AjaxRequest is a JavaScript class designed to make dealing 
 * with XMLHttpRequests (or the IE versions thereof) simplier.
 *
 * Example usage:
 * <pre>
 * &lt;input type="text" name="foo" onchange="update();"/&gt;
 * ....
 * function update() {
 *  	var req = new AjaxRequest();
 *	req.get(
 *		{ 
 *		'url'		: "/ajax/update.action",
 *		'onSuccess'	: updateCallback,
 *		'onLoading'	: function () { throbber(true); },
 *		'onDone' 	: function() { setTimeout('throbber(false);',250); }
 *		});
 * }
 *
 * function updateCallback(req) { // This is the required signature for a callback
 *	if (req.responseXML) {
 * 		// process xml file in javascript
 *	}
 * }
 * </pre>
 *
 * @version 0.2
 * @author Marcus R. Breese <mbreese@gmail.com>
 * @license Apache License, 2.0
 * Copyright 2005 Fourspaces Consulting, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @class
 * @constructor
 */
function AjaxRequest() {
	var request = new Object();
	var done = false;

	request.params = new Array();
	request.headers = new Array();

	// available callback functions	
	request.onLoading = false;
	request.onLoaded = false;
	request.onInteractive = false;
	request.onDone = false;
	request.onSuccess = false;
	request.onFail = false;

	// http request params
	request.method = "GET";
	request.async = true;
	request.username = false;
	request.password = false;
	request.url = false;
	
	request.xmlHttpRequest = AjaxRequest.getXMLHttpRequest();
	if (!request.xmlHttpRequest) {
		alert("Error creating XMLHttpRequest object!");
		return;
	}
	
	/**
	 * The onreadystatechange function for the new XMLRequest object
	 * This function takes care of all of the event processing.
	 *
	 * (It must be a part of this class and declared there to have 
	 * access to the private request object)
	 */
	request.xmlHttpRequest.onreadystatechange = function() {
		if (request.xmlHttpRequest.readyState == 1) {
			if (typeof request.onLoading == 'function' ) {
				request.onLoading(request.xmlHttpRequest);
			}
		} else if (request.xmlHttpRequest.readyState == 2) {
			if (typeof request.onLoaded == 'function' ) {
				request.onLoaded(request.xmlHttpRequest);
			}
		} else if (request.xmlHttpRequest.readyState == 3) {
			if (typeof request.onInteractive == 'function' ) {
				request.onInteractive(request.xmlHttpRequest);
			}
		} else if (request.xmlHttpRequest.readyState == 4) {
			done = true;
			if (typeof request.onDone == 'function' ) {
				request.onDone(request.xmlHttpRequest);
			}
			if (request.xmlHttpRequest.status==200) {
				if (typeof request.onSuccess == 'function' ) {
					request.onSuccess(request.xmlHttpRequest);
				}
			} else {
				if (typeof request.onFail == 'function' ) {
					request.onFail(request.xmlHttpRequest);
				}
			}
		}
	}

	/**
	 * Returns the completion state of this request
	 * @return {Boolean} if this request is complete
	 */
	 this.isDone = function() { return done; }
	
	/**
	 * Aborts the current request (if in progress)
	 */
	 this.abort = function() { 
	 	if (request.xmlHttpRequest.readyState>0) {
			request.xmlHttpRequest.abort();
		}
	 }

	/**
	 * Send an AJAX get request
	 * @param {Array} p Parameters in an associative array
	 */
	this.get = function(p) {
		this._processParameters(p);
		request.method="GET";

		var added = false;
		for ( var p in request.params ) {
			if (!added) {
				request.url+="?";
				added=true;
			} else {
				request.url+="&";
			}
			request.url+=encodeURIComponent(p)+"="+encodeURIComponent(request.params[p]);
		}

		this._send(null);
	}
	
	/**
	 * Send an AJAX post request - Included for completeness... not normally used.
	 * @param {Array} p Parameters in an associative array
	 */
	this.post = function(p) {
		this._processParameters(p);
		request.method="POST";
		
		var queryParameters = "";
		for ( var p in request.params ) {
			if (queryParameters) {
				queryParameters+="&";
			}
			queryParameters+=encodeURIComponent(p)+"="+encodeURIComponent(request.params[p]);
		}
		
		
		this._send(queryParameters);
	}
	
	/**
	 * @private
	 * Sends this request 
	 * (used internally by <a href="#get">get()</a>)
	 */
	this._send = function(queryParameters) {
		if (done) {
			alert("This request has already been completed!");
		}
		if (!request.url) {
			alert("null ajax url!");
		}
		
		if (!request.username) { request.username=null; }
		if (!request.password) { request.password=null; }
		
	
		request.xmlHttpRequest.open(request.method, request.url, request.async, request.username,request.password);
		
		for ( var h in request.headers ) {
			request.xmlHttpRequest.setRequestHeader(h,request.headers[h]);
		}
		
		if (request.method=="POST") {
			request.xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
		
		
		request.xmlHttpRequest.send(queryParameters);
	}
	
	
	/**
	 * @private
	 * Processes the parameters for this request.
	 * 
	 * In order to set get parameters set the key 'params' to an array 
	 * containing key:value pairs for the get url.
	 * 
	 * (used internally by <a href="#get">get()</a>)
	 * @param {Array} params The associative array used to store parameters
	 */
	this._processParameters = function(params) {		
		//
		// process parameters passed
		//
		
		for ( var p in params ) {
			if (request[p] != undefined) {	// this is a request parameter or callback
				request[p] = params[p];
			}
		}
	}
}

/**
 * Static method for retrieving a new XMLHttpRequest object 
 * (or the IE variant). See http://www-128.ibm.com/developerworks/web/library/wa-ajaxintro1.html?ca=dgr-lnxw01MasterAJAX
 * @returns {XMLHttpRequest} browser's request object
 */
AjaxRequest.getXMLHttpRequest = function () {
    var xmlHttp = false;

    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xmlHttp = false;
        }
    }
    @end @*/

    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
        xmlHttp = new XMLHttpRequest();
    }
    return xmlHttp;
}


Documentation generated by JSDoc on Thu Mar 2 20:22:37 2006