jQuery $.ajax() Method
The $.ajax() method is the most powerful and flexible AJAX method in jQuery. It gives you full control over every aspect of an HTTP request — method type, headers, data format, success handling, error handling, and more. All other jQuery AJAX shortcuts like $.get() and $.post() are built on top of $.ajax().
Basic Syntax
$.ajax({
url: "server-endpoint",
type: "GET", // or "POST", "PUT", "DELETE"
data: { }, // data to send (optional)
dataType: "json", // expected response format
success: function(response) {
// runs when request succeeds
},
error: function(xhr, status, error) {
// runs when request fails
}
});
Important $.ajax() Options
| Option | Purpose | Default |
|---|---|---|
| url | The server URL to send the request to | Current page |
| type | HTTP method: GET, POST, PUT, DELETE | GET |
| data | Data sent to the server | none |
| dataType | Expected response type: json, html, text, xml | auto-detect |
| success | Callback when request succeeds | none |
| error | Callback when request fails | none |
| complete | Callback when request finishes (success or error) | none |
| async | true = asynchronous, false = synchronous | true |
| timeout | Milliseconds before request times out | 0 (no limit) |
| contentType | Content type of data sent to server | application/x-www-form-urlencoded |
| headers | Extra HTTP headers to send | none |
| beforeSend | Callback that runs before the request starts | none |
Diagram: $.ajax() Request Lifecycle
$.ajax() called
│
beforeSend() runs → show loading spinner
│
HTTP request sent to server
│
├── Server responds OK → success() runs → hide spinner
│
└── Server responds ERROR → error() runs → show error msg
│
complete() runs ALWAYS (after success or error)
GET Request — Fetch JSON Data
$(document).ready(function() {
$.ajax({
url: "https://api.example.com/users",
type: "GET",
dataType: "json",
success: function(data) {
$.each(data, function(i, user) {
$("#userList").append("<li>" + user.name + " — " + user.email + "</li>");
});
},
error: function(xhr, status, error) {
$("#errorMsg").text("Failed to load users: " + error);
}
});
});
POST Request — Send Form Data
$(document).ready(function() {
$("#loginForm").submit(function(e) {
e.preventDefault();
$.ajax({
url: "login.php",
type: "POST",
data: {
username: $("#username").val(),
password: $("#password").val()
},
dataType: "json",
success: function(response) {
if (response.status === "ok") {
window.location.href = "dashboard.html";
} else {
$("#loginError").text(response.message);
}
},
error: function() {
$("#loginError").text("Server error. Please try again.");
}
});
});
});
Using beforeSend and complete for Loading State
$.ajax({
url: "data.json",
type: "GET",
beforeSend: function() {
$("#loader").show();
$("#content").hide();
},
success: function(data) {
$("#content").html(data.html).show();
},
error: function() {
$("#errorBox").text("Could not load data.").show();
},
complete: function() {
$("#loader").hide(); // always hides the loader
}
});
Diagram: Loading Spinner Pattern
User clicks button
│
beforeSend → spinner appears, content hides
│
Request in progress...
│
success → content updates and shows
complete → spinner hides
(If error: error msg shows, spinner still hides via complete)
Setting a Request Timeout
$.ajax({
url: "slow-api.php",
type: "GET",
timeout: 5000, // 5 seconds max wait
success: function(data) {
console.log(data);
},
error: function(xhr, status) {
if (status === "timeout") {
alert("Request timed out. Please try again.");
}
}
});
Sending JSON in a POST Request
$.ajax({
url: "api/save",
type: "POST",
contentType: "application/json",
data: JSON.stringify({
name: "Ravi",
age: 28,
city: "Delhi"
}),
dataType: "json",
success: function(response) {
console.log("Saved:", response.id);
}
});
Promise-Style with .done() .fail() .always()
Since jQuery 1.8, $.ajax() returns a Deferred object. You can attach callbacks using promise-style chaining instead of options.
$.ajax({ url: "data.json", type: "GET" })
.done(function(data) {
console.log("Success:", data);
})
.fail(function(xhr, status, error) {
console.log("Error:", error);
})
.always(function() {
$("#loader").hide();
});
Quick Summary
$.ajax()is the full-featured jQuery AJAX method with all options.- Key options:
url,type,data,dataType,success,error,complete. - Use
beforeSendandcompleteto show and hide loading indicators. - Set a
timeoutto handle slow server responses gracefully. - Use promise chaining (
.done(),.fail(),.always()) for cleaner code structure.
