jQuery Ajax: ajax(), get(), post() and getJSON()
Ajax means getting or sending data to the server in the background, without reloading the page. jQuery makes Ajax easy and the same in all browsers. In this chapter the examples run against a small local web server, so the outputs are real.
$.getJSON(): get JSON data
[
{ "id": 1, "name": "Anita", "city": "Delhi" },
{ "id": 2, "name": "Ravi", "city": "Pune" }
]
<ul id="users"></ul>
$.getJSON('users.json', function (users) {
$.each(users, function (i, u) {
$('<li>').text(u.name + ' (' + u.city + ')').appendTo('#users');
});
});
<ul id="users">
<li>Anita (Delhi)</li>
<li>Ravi (Pune)</li>
</ul>
$.get(): get any data
Hello from the server
<p id="out"></p>
$.get('hello.txt', function (data) {
$('#out').text(data.trim());
console.log('Received: ' + data.trim());
});
Received: Hello from the server
$.post(): send data
<p>Page</p>
$.post('save', { name: 'Anita', city: 'Delhi' }, function (response) {
console.log('Server received: ' + response.received);
console.log('Method: ' + response.method);
}, 'json');
Server received: name=Anita&city=Delhi
Method: POST
The data object is sent as name=Anita&city=Delhi. The test server only repeats what it receives.
$.ajax(): full control
The method $.ajax() has many settings. The other methods are shortcuts for it.
$.ajax({
url: 'users.json',
method: 'GET',
dataType: 'json',
success: function (data) {
console.log('Success: ' + data.length + ' users');
},
error: function (xhr, status, error) {
console.log('Error: ' + status);
},
complete: function () {
console.log('Request complete');
}
});
Success: 2 users
Request complete
Promise style: done(), fail() and always()
Ajax methods return an object which you can chain with .done(), .fail() and .always(). It is easier to read than many nested callbacks.
$.getJSON('users.json')
.done(function (users) { console.log('Done: ' + users[0].name); })
.fail(function () { console.log('Failed'); })
.always(function () {
console.log('Always runs');
// a second request, for a file which does not exist
$.getJSON('missing.json')
.done(function () { console.log('Done (missing)'); })
.fail(function (xhr) { console.log('Failed with status ' + xhr.status); });
});
Done: Anita
Always runs
Failed with status 404
Important settings of $.ajax()
| Setting | Meaning |
|---|---|
url | The address of the request |
method (or type) | GET, POST, PUT, DELETE |
data | Data to send (object or string) |
dataType | The type you expect: json, html, text, xml |
contentType | The type of the data you send. For a JSON body use 'application/json' |
headers | Extra headers, for example an API token |
timeout | Time in milliseconds after which the request fails |
cache | Set to false to avoid the browser cache for GET |
Send JSON in the body
$.ajax({
url: '/api/users',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ name: 'Anita' }),
dataType: 'json'
}).done(function (res) {
console.log(res);
});
Rules and tips
- Same origin policy: by default, the browser allows requests only to the same domain. For another domain, the server must send CORS headers.
- The request is asynchronous. The line after
$.ajax()runs before the answer comes. Put the code that needs the data inside the callback. - Always handle errors (
failorerror), because the network can fail. - Do not trust data from the server blindly. Use
.text()to show text from outside. - Never put secret keys (API secrets) in a JavaScript file, because everybody can see it.
- Today, many developers use the native
fetch()API for new code. See jQuery vs Vanilla JavaScript.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |