Low-Level AJAX with ajax()
In this page:
1. What is ajax()?
$.ajax() is the low-level method every jQuery AJAX shortcut ($.get, $.post, $.getJSON) is actually built on top of internally. Using it directly gives you full control over the request's options — method, headers, timeouts, and callbacks — when the shortcuts aren't flexible enough for what you need.
Example: 1. What is ajax()?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({url: "data.php", success: function(data) {
console.log(data);
}});
</script>
</body>
</html>
2. GET Requests
Use GET when you only need to read data from the server, such as fetching a list of products or a user's profile. The response arrives in the success callback (or the done() handler on the returned promise), ready to use once it comes back.
Example: 2. GET Requests
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({url: "data.php", method: "GET", success: function(data) {
console.log(data);
}});
</script>
</body>
</html>
3. POST Requests
Use POST when you're sending data to the server to create or update something, like submitting a form or saving a comment. The data option holds the values to send, and jQuery serializes them into the request body for you.
Example: 3. POST Requests
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({url: "data.php", method: "POST", data: {name: "Alice"}, success: function(response) {
console.log(response);
}});
</script>
</body>
</html>
4. Request Options
The ajax() method accepts many configuration options beyond the URL and data. timeout limits how long to wait before giving up, dataType tells jQuery how to parse the response, contentType describes what you're sending, and beforeSend lets you modify the request just before it goes out (for example, to add an auth header).
Example: 4. Request Options
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: "data.php",
timeout: 5000,
dataType: "json",
success: function(data) { console.log(data); }
});
</script>
</body>
</html>
5. Handling Errors
The error callback fires whenever the request fails — a network problem, a timeout, or a server error status. It receives the jqXHR object, a status text, and an error message, which together are usually enough to diagnose what went wrong without guessing.
Example: 5. Handling Errors
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: "data.php",
error: function(jqXHR, statusText, errorMsg) {
console.log(statusText, errorMsg);
}
});
</script>
</body>
</html>
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: