Skip to content

Instantly share code, notes, and snippets.

@gfscott
Created June 17, 2016 19:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfscott/4c728a7700c691d5f0f819c2ad666a8d to your computer and use it in GitHub Desktop.
Save gfscott/4c728a7700c691d5f0f819c2ad666a8d to your computer and use it in GitHub Desktop.
A simple, reusable AJAX helper function for GETting JSON
// -----------------------------------------------------------------------------
// SIMPLE REUSABLE AJAX GET JSON FUNCTION
// A frequent thing I find myself writing in projects is a simple function to
// get JSON via AJAX. This simple helper does that in a sensible way without
// needing jQuery or a needlessly complex standalone Ajax library. Get data
// so you can do stuff with it. That’s all it does. No POSTing, no crazy edge-
// case error handling.
function getJson(url, callback) {
"use strict";
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var json = JSON.parse(request.responseText);
callback(json);
} else {
// server error
console.error("There was an error connecting to the server. The error code was " + request.status);
return;
}
};
request.onerror = function() {
console.error( "There was an error connecting to the server." );
return;
};
request.send();
}
// USAGE:
//
// getJson("https://randomuser.me/api/", function(data){
// // Do stuff with the returned data
// console.log(data.results[0].name.first);
// });
@radoslawbialek
Copy link

Great job! It's very helpful. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment