While methods like load() and $.post() are great for simple
tasks, $.ajax() is the "master" method. It provides complete control over
every aspect of an HTTP request, including timeouts, headers, specific error handling,
and data formatting.
The $.ajax() method takes a single object containing all the settings for the
request.
$.ajax({
url: "test.php", // Where to send the request
type: "POST", // GET or POST
data: { id: 123 }, // Data to send
dataType: "json", // Type of data we expect back
success: function(res) {
// Runs if the request succeeds
},
error: function(xhr) {
// Runs if the request fails
}
});
Here are the most important settings you can use within the $.ajax() object:
| Key | Description |
|---|---|
url |
A string containing the URL to which the request is sent. |
method |
The type of request (e.g., "GET", "POST", "PUT", "DELETE"). |
data |
Data to be sent to the server (object or string). |
dataType |
The type of data you expect from the server (json, xml, html, text). |
timeout |
Set a timeout (in milliseconds) for the request. |
beforeSend |
A function to run **before** the request is sent (e.g., show a loading spinner). |
When handling sensitive or complex operations like a user login, $.ajax() is
the best choice because it allows you to handle both success and specific server errors
gracefully.
$.ajax({
url: "login.php",
method: "POST",
data: $("#loginForm").serialize(),
beforeSend: function() {
$("#status").text("Logging in...").show();
},
success: function(data) {
if(data.success) {
window.location.href = "dashboard.php";
} else {
$("#status").text("Invalid credentials.").addClass("text-danger");
}
},
error: function() {
alert("Server is currently unreachable. Please try again later.");
},
complete: function() {
// Always runs after success OR error
$("#spinner").hide();
}
});
$("#form").serialize() method. It
turns an entire form's inputs into a clean string ready for AJAX transmission
automatically!
beforeSend and complete.PUT and
DELETE.dataType: "json" setting when
communicating with modern APIs. It ensures jQuery parses the result for you so you can
access response.name immediately.