jQuery - What is an AJAX Success Callback?
1. What is an AJAX Success Callback?
In AJAX (Asynchronous JavaScript and XML), you make requests to a server without reloading the page.
-
A success callback is a function that runs when the AJAX request completes successfully.
-
It usually receives the response data from the server as a parameter, so you can use it to update your webpage dynamically.
2. Syntax Example
$.ajax({
url: "example.php", // URL to request
type: "GET", // Request method (GET or POST)
dataType: "json", // Expected data type from server
success: function(response) {
console.log("Data received:", response);
$("#result").html(response.message); // Display response in HTML
},
error: function(xhr, status, error) {
console.log("Error:", error);
}
});
Explanation
-
url: The server endpoint you are requesting. -
type: Method of request (GETorPOST). -
dataType: Expected type of response (JSON, HTML, text, etc.). -
success: This function executes if the server responds successfully.-
response(or any name you give) holds the data sent by the server. -
Inside this function, you can update the DOM, alert messages, or manipulate data.
-
-
error: Executes if there’s a problem with the request.
3. Real Example
Assume example.php returns this JSON:
{ "message": "Hello from the server!" }
Then your AJAX call:
$.ajax({
url: "example.php",
type: "GET",
dataType: "json",
success: function(response) {
$("#result").text(response.message);
}
});
✅ Result: The HTML element with id result will show:
Hello from the server!
4. Key Points
-
Success callback only runs if the HTTP request is successful (status 200).
-
You can pass multiple actions inside it.
-
You can also use shorthand methods like:
$.get("example.php", function(response){
$("#result").html(response.message);
});
-
Modern alternative:
.done()with$.ajax():
$.ajax("example.php").done(function(response){
$("#result").html(response.message);
});