This is my attempt to explain AJAX with no JS-specific concepts. Some understanding of C-like syntax and how functions work is needed.
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
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).
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.
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"]
}
We have a request that goes out to the server, gets some JSON, and then calls another function once the data has come back.
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()
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()