Skip to content

Instantly share code, notes, and snippets.

@edavis25
Last active March 30, 2017 05:21
Show Gist options
  • Save edavis25/c5c05010871f69001cdac4ab46ec0c26 to your computer and use it in GitHub Desktop.
Save edavis25/c5c05010871f69001cdac4ab46ec0c26 to your computer and use it in GitHub Desktop.
A couple functions for creating AJAX requests.
/**
* The postAjaxRequest and getAjaxRequst take arguments for a callback function, url, and param string.
* Both requests return the response text using "this" inside of the callback function.
*/
// POST request
function postAjaxRequest(callback, url, args) {
var contentType = 'application/x-www-form-urlencoded';
var ajax = new createAjaxObject(callback);
if (!ajax) {
return false;
}
ajax.open('POST', url, true);
ajax.setRequestHeader('Content-type', contentType);
ajax.setRequestHeader('Content-length', args.length);
ajax.setRequestHeader('Connection', 'close');
ajax.send(args);
return true;
}
// GET request
function getAjaxRequest(callback, url, args) {
// Ensure cached call is not used
var nocache = '&nocache=' + Math.random() * 1000000;
var ajax = new createAjaxObject(callback);
if (!ajax) {
return false;
}
ajax.open('GET', url + '?' + args + nocache, true);
ajax.send();
return true;
}
// Create the AJAX object. Nested Try/Catch blocks to accomodate different browsers
function createAjaxObject(callback) {
var ajax;
try {
ajax = new XMLHttpRequest();
}
catch (ex1) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (ex2) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (ex3) {
ajax = false;
}
}
}
if (ajax) {
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 && this.responseText != null) {
callback.call(this.responseText);
}
};
}
return ajax;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment