Ajax
Making requests with ease.
- Supports
GET,POST,PUT,DELETEandJSONP. new ML.Ajax({ ... })sends the request straight away. There is no separateinit()orsend().- 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 asjsonpCallback. - 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.
<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>// 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.
Callbacks
Section titled “Callbacks”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.
datais an object of names and values, which is URL-encoded, or a query string that is already encoded ('a=1&b=2', without the?). ForPOST,PUTandDELETEit is the body. ForGETandJSONPit is added to the URL, after a?or, if the URL has a query string already, after a&.headersare added to the defaultContent-type: application/x-www-form-urlencoded. A header with the same name (the case does not matter) replaces the default, soheaders: { 'Content-type': 'application/json' }sends that one only. Note thatdatais always sent URL-encoded.- A
urlcan be any text that is not empty.'', and a value that is not text, are rejected with “Not a valid URL.” cors: truesetsxhr.withCredentials, which sends cookies. The server must then answer withAccess-Control-Allow-Credentials: trueand a specific origin, not*. A request to a server that allows any origin needs no option at all.JSONPcannot report failures, because a<script>has no status:successanderrorare 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.
Enhancements
Section titled “Enhancements”A checklist. An unticked item is not built, and not promised: it says what is missing today. A ticked item has been built.
-
datawithGET. It was ignored forGET, and a stringdatawas ignored for every method. ForGETit is in the URL now, and a string is sent as it is. - Merging
headers. They replaced the defaultContent-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 setswithCredentials, which sends cookies, and makes a request fail against a server that answersAccess-Control-Allow-Origin: *. -
FormData, progress and defaults. Sending aFormData, 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.