jQuery: AJAX
jQuery has some AJAX helper methods that save time and are much easier to read. They are all properties of the $
variable: $.get
, $.post
, and $.ajax
.
$.ajax
is the main method, allowing you to manually construct your AJAX request - the others are shortcuts to common configurations, like getting data or posting it.
Here’s an example that gets some data from a server:
$.ajax({
url: '/data.json',
method: 'GET',
success: function (data) {
console.log(data);
}
});
You can see that a configuration object is used to tell jQuery how to get the data. The basics are supplied: a URL, the method (which actually defaults to get
) and a function to be called when the data is retrieved, named the success callback.
$.get
This example is just getting some data and, because this is a very common activity, jQuery provides a helper: $.get
.
$.get('/data.json', function (data) {
console.log(data);
});
You can also provide an error callback, which will let you know if something goes wrong and the server can’t be reached:
$.get('/data.json', function (data) {
console.log(data);
}).fail(function () {
// Uh oh, something went wrong
});
$.post
Sending data to a server is just as easy, using the $.post
method. The second argument is the data to be sent - it can be almost anything except a function: jQuery will figure out how to send it for you. How convenient!
$.post('/save', { username: 'tom' }, function (data) {
console.log(data);
}).fail(function () {
// Uh oh, something went wrong
});
$.ajax
Of course, if you want more control over how data is sent, use $.ajax
to set the request up manually.
$.ajax({
url: '/save',
method: 'POST',
data: { username: 'tom' },
success: function (data) {
console.log(data);
}),
error: function () {
// Uh oh, something went wrong
}
});