Skip to content

Instantly share code, notes, and snippets.

@Kyle-Falconer
Created October 25, 2013 19:31
Show Gist options
  • Save Kyle-Falconer/7160507 to your computer and use it in GitHub Desktop.
Save Kyle-Falconer/7160507 to your computer and use it in GitHub Desktop.
xhr functions for GET and POST (currently meant for Chrome only)
/*global window */
window['DEBUG'] = window['DEBUG'] || 1;
function xhr_GET(method, url, callback, opt_args){
/* http://developer.chrome.com/extensions/xhr.html */
if (window['DEBUG']){ window.console.log('making xhr GET request for url: '+url);}
var timeout= 2000;
var xhr = new window.XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onerror = function(){
console.error("error: "+xhr.statusText);
}
xhr.onload = function() {
if (xhr.status === 200) {
window.console.log("response: "+xhr.response);
var response = '';
try{
response = JSON.parse(xhr.response);
} catch (e){
response = 'error';
window.console.log('JSON parsing error; could not parse response: ', e);
}
callback(response);
} else {
console.error(xhr.statusText);
}
};
xhr.timeout = timeout;
if (typeof opt_args != 'undefined'){
url = url + '?' + opt_args;
}
xhr.open('GET', url, true);
xhr.send();
}
function xhr_POST(url, callback, opt_args){
/* http://developer.chrome.com/extensions/xhr.html */
if (window['DEBUG']){ window.console.log('making xhr POST request for url: '+url);}
var timeout= 2000;
var xhr = new window.XMLHttpRequest();
xhr.ontimeout = function () {
console.error("The request for " + url + " timed out.");
};
xhr.onerror = function(){
console.error("error: "+xhr.statusText);
}
xhr.onload = function() {
if (xhr.status === 200) {
window.console.log("response: "+xhr.response);
var response = '';
try{
response = JSON.parse(xhr.response);
} catch (e){
response = 'error';
window.console.log('JSON parsing error; could not parse response: ', e);
}
callback(response);
} else {
console.error(xhr.statusText);
}
};
xhr.timeout = timeout;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
if (typeof opt_args != 'undefined'){
xhr.send(opt_args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment