/** * Class : JSL.ajax * This class has all the ajax functions. * Based on jxs V2.01.A - http://www.openjs.com/scripts/jx/ * Example: JSL.ajax("http://www.example.com").load(function(data) { * alert(data); //data has the data fetched from the given url * }); * Arguments: URL - the url of the page to be loaded */ (function() { function _ajax_init(url) { this.url = url; this._init(); if(!url) return false; return this; } _ajax_init.prototype = { "http" : false, //HTTP Object "format" : 'text', "callback" : false, ///This is a user specified function "error" : false, ///Create a xmlHttpRequest object - this is the constructor. "_getHTTPObject" : function() { var http = false; //Use IE's ActiveX items to load the file. if(typeof ActiveXObject != 'undefined') { try {http = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { try {http = new ActiveXObject("Microsoft.XMLHTTP");} catch (E) {http = false;} } //If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document. } else if (XMLHttpRequest) { try {http = new XMLHttpRequest();} catch (e) {http = false;} } return http; }, /** * This loads the URL provided in the constructor and calls the 'callback' user function * with the data from the URL as its argument. * Arguments: * callback - Function that must be called once the data is ready. [OPTIONAL] * format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, * the string will be 'eval'ed before it is returned it. Defaults to 'text'. [OPTIONAL] * method - GET or POST. Defaults to 'GET'. [OPTIONAL] * Example: * JSL.ajax("http://www.example.com/get_data.php?hello=world&foo=bar").load(function(data) { * alert(data); * }, "text", "POST"); */ "load" : function (callback, format, method, opt) { var http = this._init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE var url = this.url; if(!http||!url) return; this.callback=callback; method = method||"GET";//Default method is GET format = format||"text";//Default return type is 'text' this.format = format.toLowerCase(); method = method.toUpperCase(); var ths = this;//Closure //XML Format need this for some Mozilla Browsers if(format == 'xml' && http.overrideMimeType) http.overrideMimeType('text/xml'); //Kill the Cache problem in IE. var now = "uid=" + new Date().getTime(); url += (url.indexOf("?")+1) ? "&" : "?"; url += now; var parameters = null; if(method=="POST") { var parts = url.split("\?"); url = parts[0]; parameters = parts[1]; } http.open(method, url, true); if(method=="POST") { http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", parameters.length); http.setRequestHeader("Connection", "close"); } if(opt.handler) { //If a custom handler is defined, use it http.onreadystatechange = opt.handler; } else { http.onreadystatechange = function () { /// [IGNORE] Call a function when the state changes. if(!ths) return; if (http.readyState == 4) {//Ready State will be 4 when the document is loaded. if(http.status == 200) { var result = ""; if(http.responseText) result = http.responseText; //If the return is in JSON format, eval the result before returning it. if(ths.format.charAt(0) == "j") { //\n's in JSON string, when evaluated will create errors in IE result = result.replace(/[\n\r]/g,""); result = eval('('+result+')'); } else if(ths.format.charAt(0) == "x") { //XML Return result = http.responseXML; } //Give the data to the callback function. if(ths.callback) ths.callback(result); } else { if(ths.opt.loading_text) document.getElementsByTagName("body")[0].removeChild(ths.opt.loading_text); //Remove the loading indicator element if(ths.opt.loading_indicator && document.getElementById(ths.opt.loading_indicator)) { document.getElementById(ths.opt.loading_indicator).style.display="none"; //Hide the given loading indicator. } if(ths.error) ths.error(http.status); } } } } http.send(parameters); }, /** * bind is one all encompassing function for ajax. The first argument is an associative array and * different details can be passed as that argument. First this hash must be created... *
var options = {
* 'onSuccess':alert,
* //other options go here...
* }
* Then it can be passed on to the bind() like this...
* JSL.ajax("http://www.example.com/get_data.php?hello=world&foo=bar").bind(options);
* The possible option values are listed below.
* Arguments: options - A associative array with these possible values.
* - options['onSuccess'] - Function that should be called at success - ie. readyState=4 and status=200
* - options['onError'] - Function that should be called at error
* - options['format'] - Return type of the ajax data - could be 'xml','json' or 'text'. If none is specified, it will default to 'text'
* - options['method'] - This decides with method should be used in sending the data - 'GET' or 'POST'. Defaults to 'GET'
* - options['update'] - If the ID of a valid element is given here, then the ajax call will be made, the data fetched and fed into this element using innerHTML.
* - options['loading_indicator'] - The id of the loading indicator. This will be set to display:block when the url is loading and to display:none when the data has finished loading.
* - options['loading_text'] - HTML that would be inserted into the document once the url starts loading and removed when the data has finished loading. This will be inserted into a div with class name 'loading-indicator' and will be placed at 'top:0px;left:0px;'
* Example:
* JSL.ajax('data.php?fetch=true&num=42&name=marvin').bind({
* "onSuccess":alert,
* "onError":function(status){alert("Something went wrong. Error : "+status)},
* "loading":"loading"
* });
*/
"bind" : function(user_options) {
var opt = {
'onSuccess':false,
'onError':false,
'format':"text",
'method':"GET",
'update':"",
'loading_indicator':"",
'loading_text':""
}
for(var key in opt) {
if(user_options[key]) {//If the user given options contain any valid option, ...
opt[key] = user_options[key];// ..that option will be put in the opt array.
}
}
opt.url = this.url;
if(opt.onError) this.error = opt.onError;
var div = false;
if(opt.loading_text) { //Show a loading indicator from the given HTML
if(opt.loading_indicator) div = document.getElementById(opt.loading_indicator); // If both loading_indicator and loading_text is given, use the 'loading_indicator' element as the holder for loading_text
else {
div = document.createElement("div");
div.setAttribute("style","position:absolute;top:0px;left:0px;");
div.setAttribute("class","loading-indicator");
document.getElementsByTagName("body")[0].appendChild(div);
}
div.innerHTML = opt.loading_text;
opt.loading_text=div;
}
if(opt.loading_indicator) document.getElementById(opt.loading_indicator).style.display="block"; //Show the given loading indicator.
this.load(function(data) {
if(opt.update) document.getElementById(opt.update).innerHTML = data;
if(div && !opt.loading_indicator) document.getElementsByTagName("body")[0].removeChild(div); //Remove the loading indicator
if(opt.loading_indicator) document.getElementById(opt.loading_indicator).style.display="none"; //Hide the given loading indicator.
if(opt.onSuccess) opt.onSuccess(data);// Call the onSuccess function
},opt.format,opt.method, opt);
},
"_init" : function() {return this._getHTTPObject();}
}
window.JSL["ajax"] = function(url) {
return new _ajax_init(url);
}
})();
/* :TODO:
* In bind() - opt[onFetch] - call after the 'this.http.send(parameters)' has been made
*
*/