Short requests: $.get, $.getJSON, $.post
For common cases $.ajax() has short forms: get data, get JSON, send data. They take an address, data and a response function, and return the same request object with done(), fail() and always(). This lesson's code works with the server from the previous lesson, so it is shown without running.
$.getJSON: load JSON
// script.js
$(function () {
$.getJSON('/api/tasks', function (tasks) {
for (const task of tasks) {
$('#tasks').append($('<li>').text(task.title));
}
});
});This is the same as $.ajax() with dataType: 'json' from the previous lesson, in one line. Open the page and the task list loads from the server.
$.get: parameters in the address
$.get() makes a GET request. An object as the second argument becomes address parameters:
// script.js
$.get('/api/tasks', { done: false, limit: 10 }, function (tasks) {
console.log('Unfinished tasks:', tasks.length);
}, 'json');jQuery sends the request to /api/tasks?done=false&limit=10. The last argument, 'json', sets the response type. If the server answers with the Content-Type: application/json header, jQuery parses the response anyway and the argument can be omitted.
$.post: send data
$.post() makes a POST request and sends the data as form fields:
// script.js
$.post('/api/tasks', { title: 'Write the report' })
.done(function (task) {
$('#tasks').append($('<li>').text(task.title));
})
.fail(function () {
alert('Could not save the task');
});The server receives the title field, creates the task and returns it. If the server expects JSON specifically, use $.ajax() with contentType, as in the previous lesson.
Submitting a form
The course example: the sign-up form goes to the server without a reload. The markup in index.html:
<form id="signup">
<input name="name" placeholder="Name">
<input name="email" placeholder="Email">
<button>Sign up</button>
</form>
<p id="result"></p>The code in script.js:
// script.js
$('#signup').on('submit', function (event) {
event.preventDefault();
const $button = $(this).find('button').prop('disabled', true);
$.post('/api/signup', $(this).serialize())
.done(function () {
$('#result').text('Done, check your email');
})
.fail(function () {
$('#result').text('Error, please try again');
})
.always(function () {
$button.prop('disabled', false);
});
});serialize() collects the form fields into a string, and the button is disabled during the request so the form is not sent twice.
load: insert HTML from the server
The load() method loads an HTML fragment and inserts it into the element right away:
// script.js
$('#help').load('/help.html');Summary
| Function | Method | Response |
|---|---|---|
$.get(url, data, fn) | GET | Any |
$.getJSON(url, data, fn) | GET | JSON |
$.post(url, data, fn) | POST | Any |
$(el).load(url) | GET | HTML, inserted into the element |
The same in plain JavaScript
// script.js
const response = await fetch('/api/tasks');
const tasks = await response.json();Common mistake
Expecting $.post() to send JSON. An object in data goes out as title=... form fields, and a server that reads the body as JSON gets empty data. Either make the server accept form fields, or send with $.ajax() using contentType: 'application/json' and JSON.stringify().