Skip to content

Instantly share code, notes, and snippets.

@Lukewh
Created December 11, 2012 15:15

Revisions

  1. Lukewh created this gist Dec 11, 2012.
    30 changes: 30 additions & 0 deletions getXHR.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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
    }
    4 changes: 4 additions & 0 deletions manifest.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    "permissions": [
    "http://atlas.metabroadcast.com/",
    "http://*.google.co.uk/"
    ]
    35 changes: 35 additions & 0 deletions postXHR.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    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();
    }
    }