Skip to content

Instantly share code, notes, and snippets.

@NigelGreenway
Created March 9, 2015 11:06
Show Gist options
  • Save NigelGreenway/500f44a9f26a8ce6ffb1 to your computer and use it in GitHub Desktop.
Save NigelGreenway/500f44a9f26a8ce6ffb1 to your computer and use it in GitHub Desktop.
Trial of my own JS AJAX module
(function(window, document, undefined) {
/**
* @returns {XMLHttpRequest|ActiveXObject}
*/
function initialise () {
if (window.XMLHttpRequest) {
// [ IE7+, FireFox, Chrome, Opera, Safari ]
return new XMLHttpRequest();
} else {
// [ IE5, IE6 ]
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
var Ajax = {
/**
* Get a resource via a URL
*
* @param string url
* @param callable callback
*/
get: function(url, callback) {
var xmlHttp = initialise();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 ) {
if (typeof callback != 'undefined') {
return callback(xmlHttp);
};
}
}
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader('X-Requested-With','XMLHttpRequest');
xmlHttp.send();
},
/**
* Put content onto the server
*
* Used to *create* or *replace* the entity content.
*
* @param string url
* @param mixed data
* @param callable callback
*/
put: function(url, data, callback) {
var xmlHttp = initialise();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (typeof callback === 'function') {
return callback(xmlHttp);
};
};
}
xmlHttp.open('PUT', url, false);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader('X-Requested-With','XMLHttpRequest');
xmlHttp.send(data);
},
/**
* Patch content on the server
*
* Used to *update* part of an entity
*
* @param string url
* @param mixed data
* @param callable callback
*/
patch: function(url, data, callback) {
var xmlHttp = initialise();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (typeof callback == 'function') {
return callback(xmlHttp);
}
}
}
xmlHttp.open('PATCH', url, false);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlHttp.send(data);
},
/**
* Delete a resource from the server
*
* Used to *remove* an entity
*
* @param url
* @param callback
*/
delete: function(url, callback) {
var xmlHttp = initialise();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (typeof callback === 'function') {
return callback(xmlHttp);
};
};
}
xmlHttp.open('DELETE', url, false);
xmlHttp.setRequestHeader('X-Requested-With','XMLHttpRequest');
xmlHttp.send();
}
}
window.Ajax = Ajax;
if (typeof define === 'function' && define.amd) {
define(Ajax);
};
}) (window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment