Last active
March 30, 2017 05:21
-
-
Save edavis25/c5c05010871f69001cdac4ab46ec0c26 to your computer and use it in GitHub Desktop.
A couple functions for creating AJAX requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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