Notes

AJAX

Edit on GitHub


APIs
2 minutes

AJAX XMLHttpRequest()

 1const xhr = new XMLHttpRequest();
 2
 3xhr.open('GET', url);
 4xhr.onload = function() {
 5  if(xhr.status === 200) {
 6    console.log(xhr.response)
 7  }
 8};
 9xhr.onerror = function() {};
10xhr.send();

onReadyStateChange has been around since original spec. In v2, onload, onprogress and onerror were introduced, which are basically different states. Instead of defining a function that looks for onReadyStateChange === 4, you can use the onload function, which is more to the point and less typing.s

  • onReadyStateChange === 4 is the same as onload
  • onReadyStateChange === 3 is the same as onprogress

CORS

When CORS is not supported, you’ll pull your hair. One solution is adding http://crossorigin.me/ at the beginning of your resource URL. But this only works for images, for JSON objects, it converts them to plain text. CrossOrigin.me

jQuery works out of the box with jsonp enabled endpoints. I tried working with XMLHttpRequest in vanilla JS but because of CORS disabled, had to fall back to jQuery.

jQuery and JSONP

 1$.ajax({
 2  url: "http://api.forismatic.com/api/1.0/",
 3  dataType: "jsonp",
 4  jsonp: "jsonp", // this was required by Forismatic
 5  data: {
 6    method: "getQuote",
 7    lang: "en",
 8    format: "jsonp"
 9  },
10  success: function(response) {
11    console.log(response);
12  }
13});

React and AJAX

React has complimentary libraries that handle HTTP requests really well. The most common one being Axios. Axios doesn’t handle JSONP though. reqwest does.

Fetch API

The Fetch API provides an interface for fetching resources (including across the network).

does not support JSONP

npm JSONP

JSONP is a node package.

1npm install jsonp --save
1var jsonp = require('jsonp');
2
3jsonp('http://www.example.com/foo', null, function (err, data) {
4  if (err) {
5    console.error(err.message);
6  } else {
7    console.log(data);
8  }
9});

Read more