The $.ajax Method
Full control over any request with the low-level $.ajax().
Syntax
$.ajax({ url, method, dataType }).done(fn).fail(fn);$.ajax() is the complete request method — every shorthand is built on it. You pass a settings object and attach handlers.
$.ajax({
url: "/api/data",
method: "GET",
dataType: "json"
})
.done(function (data) { /* success */ })
.fail(function (err) { /* error */ })
.always(function () { /* runs either way */ });Use .done(), .fail(), and .always() to handle each outcome.
Example
Loading editor…
Press Run to see the result.
When to use it
- An authenticated API client uses $.ajax() with a custom Authorization header that $.get() cannot set.
- A file-upload progress bar uses $.ajax() with xhr: function() to subscribe to the XHR progress event.
- A multi-tenant app uses $.ajax() with a beforeSend hook to inject a tenant ID header into every request.
More examples
Full $.ajax() with custom headers
The headers option lets $.ajax() send any custom HTTP header, which shorthand $.get() does not support.
<button id="req">Authenticated request</button>
<p id="out"></p>
<script>
$(function () {
$("#req").click(function () {
$.ajax({
url: "/api/profile",
method: "GET",
headers: { "Authorization": "Bearer mytoken123" },
success: function (d) { $("#out").text("Name: " + d.name); },
error: function (xhr) { $("#out").text("Error: " + xhr.status); }
});
});
});
</script>PUT request to update a resource
Setting contentType to application/json and manually calling JSON.stringify() sends a proper JSON body for REST APIs.
<input id="title" value="New title" />
<button id="update">Update</button>
<p id="res"></p>
<script>
$(function () {
$("#update").click(function () {
$.ajax({
url: "/api/posts/42",
method: "PUT",
contentType: "application/json",
data: JSON.stringify({ title: $("#title").val() }),
success: function (d) { $("#res").text("Updated: " + d.title); }
});
});
});
</script>beforeSend hook to inject tenant header
The beforeSend callback receives the raw XHR object, allowing you to set headers immediately before the request fires.
<button id="req">Load data</button>
<p id="out"></p>
<script>
$(function () {
$("#req").click(function () {
$.ajax({
url: "/api/data",
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Tenant-ID", "acme-corp");
},
success: function (d) {
$("#out").text(JSON.stringify(d));
}
});
});
});
</script>
Discussion