Example 1 — Basic GET with .done()
Fetch JSON and read a field when the request succeeds.
$("#load").on("click", function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET"
}).done(function (data) {
$(".log").text("Title: " + data.title);
}).fail(function () {
$(".log").text("Request failed.");
});
});
Click #load → $.ajax() sends GET
On success → .log shows "Title: …"
On failure → .log shows "Request failed."
How It Works
- Click. The handler calls
$.ajax() with a URL and method. - Send. jQuery starts an async GET and returns a jqXHR.
- Success.
.done() receives the parsed response body.
Example 2 — POST with data
Send form-style fields in the request body and read the created resource.
$("#post").on("click", function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
method: "POST",
data: { title: "Hello Ajax", body: "Posted with $.ajax()", userId: 1 }
}).done(function (data) {
$(".log").text("Created id: " + data.id + " — " + data.title);
});
});
Click #post → POST with title/body/userId
Server echoes created resource
.log shows "Created id: … — Hello Ajax"
How It Works
- Method.
method: "POST" puts data in the body (not the query string). - Encode. By default jQuery sends
application/x-www-form-urlencoded. - Response. The demo API returns JSON with an
id.
Example 3 — dataType + done / fail / always
Parse JSON automatically and chain all three promise-style handlers.
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
dataType: "json"
})
.done(function (data) {
$(".log").append("\ndone: userId=" + data.userId);
})
.fail(function () {
$(".log").append("\nfail");
})
.always(function () {
$(".log").append("\nalways (finished)");
});
Valid URL → done + always
404 URL → fail + always
always runs in both cases
How It Works
- Parse.
dataType: "json" turns the body into an object before .done(). - Success path.
.done() runs only when the request succeeds. - Error path.
.fail() runs on HTTP or parse errors.