Instantly share code, notes, and snippets.

@SamBrishes /ajax.js
Last active Jan 19, 2019

Embed
What would you like to do?
Vanilla JavaScript Handler, similar to jQuery.ajax()
/*
| A VANILLA JAVASCRIPT AJAX HANDLER
| ... similar to jQuery.ajax()
|
| @version 0.1.0
| @author SamBrishes, pytesNET
| @license Public Domain
| @article https://www.pytes.net/code/just-vanilla-06-xmlhttprequests/
|
| @param string The URL, which should be called
| @param object The respective configuration object
| -----------
| @param object The respective configuration object
*/
function ajax(){
var config = {
accepts: null,
async: true,
beforeSend: function(xhr, settings){ },
cache: "no-cache",
complete: function(xhr, status){ },
contents: { },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
context: false,
converters: {
"* text": window.String,
"text html": true,
"text json": JSON.parse,
"text xml": function(content){
var parser = new DOMParser();
return parser.parseFromString(content, "application/xml");
}
},
data: "",
dataFilter: function(data, type){ return data; },
dataType: null,
error: function(xhr, status, error){ },
// global: true,
headers: {},
// ifModified: false,
// jsonp: null,
// jsonpCallback: null,
method: "GET",
// mimeType: null,
password: null,
processData: true,
// scriptCharset: null,
statusCode: {},
success: function(data, status, xhr){ },
timeout: 0,
url: window.location.toString(),
username: null,
xhr: (typeof(ActiveXObject) == "undefined")? XMLHttpRequest: ActiveXObject,
xhrFields: {}
};
// Pass Arguments
if(arguments.length >= 2){
if(typeof(arguments[0]) != "string"){
return false;
}
if(typeof(arguments[1]) != "object"){
return false;
}
config = Object.assign(config, arguments[1], {url: arguments[0]});
} else if(arguments.length == 1){
if(typeof(arguments[0]) != "object"){
return false;
}
config = Object.assign(config, arguments[0]);
} else {
return false;
}
/*
| XHR HANDLER
*/
var xhr = new config.xhr(), self, args, text, type, key;
xhr.onreadystatechange = function(){
if(config.timeout > 0){
if((start.getTime() + config.timeout + 50) >= (new Date()).getTime()){
this.abort();
}
}
if(this.readyState !== 4){
return true;
}
self = config.context || this;
if(this.status >= 400 && this.status <= 600){
args = [this, "error", this.statusText];
} else {
args = [null, this.statusText. this];
text = config.dataFilter(this.responseText, this.responseType);
// Get Content Type
if(typeof(config.dataType) !== "string"){
type = (function(_1, _2){
if(/\/json/.test(_1) && (_2.indexOf("{") <= 2 || _2.indexOf("[") <= 2)){
return "json";
}
if(/xml/.test(_1) && _2.indexOf("<?xml") <= 2){
return "xml";
}
if(/html/.test(_1) && _2.indexOf("<") <= 2){
return "html";
}
return "text";
}(this.responseType, this.responseText));
} else {
type = config.dataType;
}
for(key in config.contents){
if((new RegExp(config.contents[key])).test(type)){
type = key;
}
}
// Convert Content
var curr = "", from, to;
for(key in config.converters){
from = key.split(" ");
to = from[1];
from = from[0];
if(from == "*"){
text = config.converters[key](text);
curr = to;
}
if(from == curr && to == type){
text = config.converters[key](text);
curr = to;
}
}
args[0] = text;
};
if(this.status in config.statusCode){
config.statusCode[this.status].apply(self, args);
} else {
if(args[1] == "error"){
config.error.apply(self, args);
} else {
config.success.apply(self, args);
}
}
config.complete.call(self, this, this.status);
}
xhr.onabort = function(){
config.error.apply(self, [this, "abort", ""]);
};
xhr.ontimeout = function(){
config.error.apply(self, [this, "timeout", ""]);
};
/*
| XHR SETUP
*/
xhr.open(config.method, config.url, config.async, config.username, config.password);
if(typeof(config.accepts) == "string"){
xhr.setRequestHeader("Accept:", config.accepts);
}
if(typeof(config.cache) == "string"){
xhr.setRequestHeader("Cache-Control", "no-cache");
}
if(typeof(config.contentType) == "string"){
xhr.setRequestHeader("Content-Type", config.contentType);
}
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
for(key in config.headers){
xhr.setRequestHeader(key, config.headers[key]);
}
for(key in config.xhrFields){
xhr[key] = config.xhrFields[key];
}
/*
| XHR SEND
*/
var start = new Date();
config.beforeSend(xhr, config);
if(config.processData === true && typeof(config.data) !== "string"){
config.data = (function parseData(data){
if(data instanceof Object){
var string = [], main = (keys)? [].concat(keys): [], pass, key;
for(key in data){
if(data[key] instanceof Object){
pass = [].concat(main);
pass.push(key);
string.push(parseData(data[key], pass));
} else {
if(main.length > 0){
pass = [].concat(main);
pass.push(key);
string.push(pass.shift() + "[" + pass.join("][") + "]=" + encodeURI(data[key]));
} else {
string.push(key + "=" + encodeURI(data[key]));
}
}
}
return string.join("&");
} else if(data === true){
return "1";
} else if(data === false){
return "0";
}
return data;
}(config.data));
}
if(config.timeout > 0){
xhr.timeout = config.timeout;
}
xhr.send(config.data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment