Skip to content

Instantly share code, notes, and snippets.

@tanvir002700
Created December 16, 2016 06:39
Show Gist options
  • Save tanvir002700/d9a4d92fa4c66f1b26c366ed2ef09bec to your computer and use it in GitHub Desktop.
Save tanvir002700/d9a4d92fa4c66f1b26c366ed2ef09bec to your computer and use it in GitHub Desktop.
Ajax Library
var Library = {};
Library.toQueryString = function(data){
if(data){
var qstring = [];
for (var key in data){
qstring.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
}
data = qstring.join("&");
return data;
}else{
return null;
}
}
Library.createXHR = function(url, options){
var xhr = false;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest;
} else if (window.ActiveXObject){
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e){
xhr = false;
}
}
if(xhr){
options = options || {};
options.method = options.method || "GET";
options.data = Library.toQueryString(options.data) || null;
if(options.cache == false && options.method.toUpperCase() == 'GET'){
url = url + "?_="+new Date().getTime();
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 1){
if(options.before){
options.before.call(xhr);
}
}
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
var contentType = xhr.getResponseHeader('Content-Type');
if(options.complete){
if(contentType == 'application/json' || contentType == 'application/octet-stream'){
options.complete.call(xhr,JSON.parse(xhr.response));
}else if (contentType == 'application/xml' || contentType == 'text/xml'){
options.complete.call(xhr, xhr.responseXML);
}else{
options.complete.call(xhr, xhr.responseText);
}
}else{
return false;
}
}
};
xhr.open(options.method,url, true);
}
return xhr;
};
Library.ajax = function(url, options){
var xhr = Library.createXHR(url,options);
if(xhr){
xhr.setRequestHeader('X-Requested-with', 'XMLHttpRequest');
if(options.method.toUpperCase() == 'POST'){
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.send(options.data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment