Skip to content

Instantly share code, notes, and snippets.

@stylesuxx
Forked from Zirak/jhr.js
Created October 4, 2013 18:11
Show Gist options
  • Save stylesuxx/6830163 to your computer and use it in GitHub Desktop.
Save stylesuxx/6830163 to your computer and use it in GitHub Desktop.
//this is a tiny helper method for making JSON Http Requests
//if you want a more comprehensive solution, write it yourself
//
//the callback function will receive two arguments: the response,
// parsed as JSON, and the xhr object used inside jhr, with an added
// responseJSON property (you can probably guess what it is)
//
//this always sends a POST request, and the data is always serialized to JSON
//
//returns the xhr object used
var JHR = function ( url, data, fun ) {
var xhr = new XMLHttpRequest();
xhr.responseJSON = null;
xhr.open( 'POST', url );
xhr.setRequestHeader( 'Content-Type', 'application/json' );
xhr.addEventListener( 'load', function () {
//my old man once told me "Zirak, sometimes, you must face the dangers
// of life head on". he then threw me in a shark tank. but I'm sure it
// applies here too.
//...I was only 7
xhr.responseJSON = JSON.parse( xhr.responseText );
fun( xhr.responseJSON, xhr );
});
xhr.send( JSON.stringify(data) );
return xhr;
};
//compatibility: anything supporting XMLHttpRequest2 http://caniuse.com/xhr2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment