Skip to content

Instantly share code, notes, and snippets.

@ssube
Last active June 17, 2016 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssube/96b8c1bf3ba036b515f8921852b7fcd1 to your computer and use it in GitHub Desktop.
Save ssube/96b8c1bf3ba036b515f8921852b7fcd1 to your computer and use it in GitHub Desktop.
eli5-ajax

ELI5: AJAX

This is my attempt to explain AJAX with no JS-specific concepts. Some understanding of C-like syntax and how functions work is needed.

What Is?

AJAX stands for asynchronous JavaScript and XML, but rarely uses XML anymore. The core of AJAX is a request to the server which will not return a value immediately, but call a function with the response later (once it's come over the wire).

MDN says: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

How Do?

In psuedo-code, AJAX works something like:

function handleResponse(data) {
  // do stuff with the data
}

fetch('http://example.com/api/something').then(handleResponse);

This uses the more modern fetch-and-promise style. Older libraries use:

get({
  url: 'http://example.com/api/something',
  success: handleResponse
});

which is JS' notation for an object (map/hash/dict-like).

Asynchronous

Because AJAX goes over the network to a server, it happens asynchronously. That is, the fetch or get function does not immediately return the data.

var data = syncThing();
asyncThing().then(data => ...);

Using the classic callback pattern, you pass a function to be called back to at a later date:

function callback(data) {
  ...
}

asyncThing(callback);

JavaScript allows function to be assigned and passed like other objects, which makes this much easier.

JSON

Requests typically return a response in JSON, which is a simple format for representing nested maps and lists. JSON is a text format similar to what JS uses when declaring objects in code, but is more strict.

Docs: http://www.json.org/

Example:

{
  "key": ["list", "of", "strings"]
}

So Far...

We have a request that goes out to the server, gets some JSON, and then calls another function once the data has come back.

For Real?

Requests in the browser use the XMLHttpRequest class, which is not terribly intuitive but does follow the patterns I've described so far.

XHR: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

You start by creating a new request:

var xhr = new XMLHttpRequest();

Then opening a URL:

xhr.open('GET', 'http://example.com/api/something', true);

The first parameter is the HTTP method (GET for loading, POST for submitting).

Next, attach a callback:

xhr.onreadystatechange = function () {
  if (xhr.status === 200) { // success
    console.log(xhr.responseText); // log the response
  }
}

To parse the response as JSON, we change that slightly:

xhr.onreadystatechange = function () {
  if (xhr.status === 200) { // success
    var data = JSON.parse(xhr.responseText);
    // do stuff with the data
  }
}

Finally, you send the request to actually talk to the server:

xhr.send()

Put Together...

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api/something', true);
xhr.onreadystatechange = function () {
  if (xhr.status === 200) { // success
    var data = JSON.parse(xhr.responseText);
    // do stuff with the data
  }
}
xhr.send()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment