Skip to content

Instantly share code, notes, and snippets.

@Lukewh
Created December 11, 2012 15:15
Show Gist options
  • Save Lukewh/4259207 to your computer and use it in GitHub Desktop.
Save Lukewh/4259207 to your computer and use it in GitHub Desktop.
function getXHR(url, callback) {
var xhr = new XMLHttpRequest(); // Creates a new XHR request
if (!url) {
throw new Error('No URL supplied');
}
xhr.open("GET", url, true); // Open the connection
xhr.setRequestHeader("Content-type",
"text/plain; charset=utf-8;");
xhr.withCredentials = "true"; // This sends cookies through
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // If the response has finished downloading
if(xhr.status === 200){ // And the content was found
try {
if (callback) {
callback(null, JSON.parse(xhr.responseText));
}
} catch(e){
throw new Error('Malformed response');
}
}
}
}
xhr.send(); // Makes the request
}
"permissions": [
"http://atlas.metabroadcast.com/",
"http://*.google.co.uk/"
]
function postXHR(url, data, callback) { // Added data to function
var xhr = new XMLHttpRequest();
if (!url) {
throw new Error('No URL supplied');
}
xhr.open("POST", url, true); // Changed "GET" to "POST"
xhr.setRequestHeader("Content-type",
"text/plain; charset=utf-8;");
xhr.withCredentials = "true";
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
if (callback) {
callback(null, JSON.parse(xhr.responseText));
}
} catch(e) {
throw new Error('Malformed response');
}
}
}
}
if (data) {
data = JSON.stringify(data); // Stringify the data Object literal
xhr.send(data); // Added the JSON stringified object.
} else {
xhr.send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment