Coverage

22%
22
5
17

/Users/sebastiansandqvist/Documents/Sites & Projects/apps/~wip/s-ajax/index.js

22%
22
5
17
LineHitsSource
1// ----- main exported object
2// ---------------------------------------
31var ajax = module.exports = {};
4
5
6// ----- reusable response methods
7// ---------------------------------------
81function onload(req, fn) {
90 if (req.status >= 200 && req.status < 400) {
100 var text = req.responseText;
110 var data = req.responseType === 'json' ? JSON.parse(text) : text;
120 return fn(null, data);
13 }
14 else {
150 return fn(new Error('Server returned an error'));
16 }
17};
18
191function onerror(fn) {
200 return fn(new Error('Connection error'));
21}
22
23
24// ----- GET requests
25// ---------------------------------------
261ajax.get = function(url, fn) {
27
280 var req = new XMLHttpRequest();
29
300 req.open('GET', url, true); // method, url, async boolean
31
320 req.onload = onload(req, fn);
330 req.onerror = onerror(fn);
34
350 req.send();
36
37};
38
39
40// ----- POST requests
41// ---------------------------------------
421ajax.post = function(url, data, fn) {
43
440 var req = new XMLHttpRequest();
45
460 req.open('POST', url, true);
470 req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
48
490 req.onload = onload(req, fn);
500 req.onerror = onerror(fn);
51
520 req.send(data);
53
54};