Skip to content

Instantly share code, notes, and snippets.

@arieh
Created September 9, 2010 08:18
Show Gist options
  • Save arieh/571574 to your computer and use it in GitHub Desktop.
Save arieh/571574 to your computer and use it in GitHub Desktop.
This is an example for my AJAX blog post
(function(window,undef){
//get a new XMLHttpRequest object
function getXHR(){
//for IE:
if (window.ActiveXObject){
try{ //newer version
return new ActiveXObject('MSXML2.XMLHTTP');
}catch (e){//older version
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
//for all other browsers
return new XMLHttpRequest();
}
window['AJAX'] = function(url,method,async){
//setting default values
method = method || "get";
async = (async === undef) ? true : async;
var complete_funcs = [] //a stack of functions to call when request is done
, headers = {"X-Requested-With":'XMLHttpRequest'} //a list of headers to send with the request
, xhr = this.xhr = getXHR(); //the request object
this.setHeader = function setHeader(key,value){
headers[key] = value;
}
//add function to the complete event
//accepts a N length list of functions
this.onComplete = function onComplete(func){
for (var i = 0; i<arguments.length; i++){
//fo through all arguments passed to the function and add them to
//the function stack
complete_funcs.push(arguments[i]);
}
}
//send the request with request data - a literal object of keys and values
this.go = function go(data){
var query = ""
, sep = "";
//go through all keys in data
for (var key in data){
if (data.hasOwnProperty(key)){
//if the key isn't derived for the prototype, add it to the reuqest query:
query += sep + encodeURIComponent(key) +"="+ encodeURIComponent(data[key]);
sep = "&";
}
}
if (method =='get'){
this.xhr.open("GET",url+"?"+query,async);
for (var key in headers){//add user headers
if (headers.hasOwnProperty(key)) xhr.setRequestHeader(key,headers[key]);
}
this.xhr.send();
}else{
this.xhr.open("POST",url,async);
for (var key in headers){//add user headers
if (headers.hasOwnProperty(key)) xhr.setRequestHeader(key,headers[key]);
}
this.xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
this.xhr.send(query);
}
}
this.xhr.onreadystatechange = function(){
//add the event handler
if (xhr.readyState == 4){//if the request is done
if (xhr.status == 200) {//and the request is valid
for (var i = complete_funcs.length-1; i>=0; i--){
//call all functions in complete stack
complete_funcs[i](xhr.responseText,xhr);
}
}
}
}
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment