Skip to content

Ajax

Making requests with ease.

  • Supports GET, POST, PUT, DELETE and JSONP.
  • new ML.Ajax({ ... }) sends the request straight away. There is no separate init() or send().
  • You can set the response type and the headers, and CORS is configurable.
  • For JSONP, define a global callback function first and pass its name as jsonpCallback.
  • The page must be served over http(s). It throws on a file:// page.

Click a button. The response is shown under it.

GET

Nothing yet.

POST

Nothing yet.

JSONP

Nothing yet.
HTML
<p>Click a button. The response is shown under it.</p>
<div class="ajax-example">
<div class="ajax-example-head">
<h4>GET</h4>
<button type="button" id="ajax-get">make request</button>
</div>
<pre id="ajax-get-output">Nothing yet.</pre>
</div>
<div class="ajax-example">
<div class="ajax-example-head">
<h4>POST</h4>
<button type="button" id="ajax-post">make request</button>
</div>
<pre id="ajax-post-output">Nothing yet.</pre>
</div>
<div class="ajax-example">
<div class="ajax-example-head">
<h4>JSONP</h4>
<button type="button" id="ajax-jsonp">make request</button>
</div>
<pre id="ajax-jsonp-output">Nothing yet.</pre>
</div>
JavaScript
// Shows a response on the page, so the demo does not need the browser console.
function show(id, value) {
document.getElementById(id).textContent = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
}
// JSONP: the response is a script that calls a global function by name, so this
// function has to be global. Its name is passed to Ajax as `jsonpCallback`.
function demoJsonpCallback(response) {
show('ajax-jsonp-output', response);
}
// GET. `new ML.Ajax(...)` sends the request straight away.
document.getElementById('ajax-get').addEventListener('click', function () {
new ML.Ajax({
url: '/demo/user.json',
responseType: 'json',
success: function (xhr) {
show('ajax-get-output', xhr.response.data);
},
error: function (xhr) {
show('ajax-get-output', 'Request failed, status ' + xhr.status);
}
});
});
// POST. `data` is URL-encoded and sent as the body. This goes to a public test
// service, so the demo shows an error here if that service is down.
document.getElementById('ajax-post').addEventListener('click', function () {
new ML.Ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
responseType: 'json',
data: {
name: 'john smith',
age: 22
},
success: function (xhr) {
show('ajax-post-output', xhr.response);
},
error: function (xhr) {
show('ajax-post-output', 'Request failed, status ' + xhr.status);
}
});
});
// JSONP. `data` goes in the URL, with `callback=demoJsonpCallback` added.
// There are no success or error callbacks: a <script> reports no status.
document.getElementById('ajax-jsonp').addEventListener('click', function () {
show('ajax-jsonp-output', 'Waiting...');
new ML.Ajax({
url: '/demo/jsonp.js',
method: 'JSONP',
data: {
name: 'john smith',
age: 22
},
jsonpCallback: 'demoJsonpCallback'
});
});

The GET and JSONP buttons read files from this site (/demo/user.json and /demo/jsonp.js). A static file cannot answer a real JSONP request, so jsonp.js just calls demoJsonpCallback and ignores the query string it is sent. The POST button sends to jsonplaceholder.typicode.com, a public test service, and shows an error if that service is down.

success(xhr) is called for a status from 200 to 299, and error(xhr) for any other, including 0 when the network or CORS blocked the request. Both receive the XMLHttpRequest, so read the result from xhr.response and the status from xhr.status.

new Ajax(...) also gives you the request as ajax.xhr, for example to call abort(). It is null for JSONP.

  • data is an object of names and values, which is URL-encoded, or a query string that is already encoded ('a=1&b=2', without the ?). For POST, PUT and DELETE it is the body. For GET and JSONP it is added to the URL, after a ? or, if the URL has a query string already, after a &.
  • headers are added to the default Content-type: application/x-www-form-urlencoded. A header with the same name (the case does not matter) replaces the default, so headers: { 'Content-type': 'application/json' } sends that one only. Note that data is always sent URL-encoded.
  • A url can be any text that is not empty. '', and a value that is not text, are rejected with “Not a valid URL.”
  • cors: true sets xhr.withCredentials, which sends cookies. The server must then answer with Access-Control-Allow-Credentials: true and a specific origin, not *. A request to a server that allows any origin needs no option at all.
  • JSONP cannot report failures, because a <script> has no status: success and error are never called. Each request adds a <script> to <body> and leaves it there. The callback name is added to the URL as it is, so only pass a name you trust.

See the generated Ajax class reference for every option.

A checklist. An unticked item is not built, and not promised: it says what is missing today. A ticked item has been built.

  • data with GET. It was ignored for GET, and a string data was ignored for every method. For GET it is in the URL now, and a string is sent as it is.
  • Merging headers. They replaced the default Content-type. They are added to it now, and one with the same name replaces it.
  • URLs that end in /. They were rejected as “Not a valid URL.” Any URL that is not empty is accepted now.
  • A JSON body. A setting that sends an object as JSON, with the header.
  • A timeout. There is none. (ajax.xhr.abort() can stop a request.)
  • Sending later. The constructor sends the request, so there is no way to make one and send it later.
  • Better JSONP. It cannot tell that a request failed, never removes its <script>, and does not encode the callback name.
  • A clearer name than cors. It sets withCredentials, which sends cookies, and makes a request fail against a server that answers Access-Control-Allow-Origin: *.
  • FormData, progress and defaults. Sending a FormData, upload progress events, and defaults shared by every request.
  • responseType: 'json' in IE10. It is probably not supported there (not tried), so the response would not be parsed.