Get and Post JSON with JavaScript

JavaScript JSON

The functions shown later will load and send JSON files with XMLHttpRequest.

Please note that 3xx redirects are treated as success with code 200 by the browser. If you need this information you have to check the response origin in the xhr object. It is not possible to detect with Internet Explorer.

function transmitJSON(method, url, toSend, callback) { var callback = callback || function() {} var xhr = new XMLHttpRequest() xhr.open(method, url) xhr.setRequestHeader('Accept', 'application/json') xhr.onload = function() { if (this.status != 200) return callback({ status: this.status, statusText: xhr.statusText }, null, xhr) else { try { var json = JSON.parse(xhr.responseText) } catch (e) { return callback({ status: 202 }, xhr.responseText, xhr) } return callback(null, json, xhr) } } xhr.onerror = function() { return callback({ status: this.status, statusText: xhr.statusText }, null, xhr) } if (!toSend) xhr.send() else { xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(JSON.stringify(toSend)) } }

loading data in JSON

transmitJSON('get', '/api/stuff', null, function(error, data, meta) { if(error) return alert('ups ' + error.statusText) // data contains the value send by the server // meta contains the xhr request })

sending data in JSON

transmitJSON('post', '/api/stuff', {data: 'I\'m data'})

of course these can be combined

Reference

No known

History May 08, 2017