AJAX with jQuery
$.ajax(), $.get() and $.post(), handling JSON responses, and how they compare to native fetch().
$.ajax() — the general-purpose method
$.ajax() is jQuery's core method for making HTTP requests without a full page reload. Every other AJAX helper ($.get, $.post) is really just a convenience wrapper around it:
$.ajax({
url: '/api/users',
method: 'GET',
dataType: 'json',
success: function (data) {
console.log('Users:', data);
},
error: function (xhr, status, error) {
console.error('Request failed:', status, error);
},
});
url— the endpoint to request.method— the HTTP verb (GET,POST,PUT,DELETE).dataType— the format jQuery should parse the response as (jsonautomatically parses the response body into a JavaScript object).success/error— callbacks for the two outcomes.
$.get() and $.post()
Shorthand helpers for the two most common cases:
$.get('/api/users', function (data) {
console.log(data);
});
$.post('/api/users', { name: 'Jane', email: 'jane@example.com' }, function (data) {
console.log('Created:', data);
});
Handling JSON responses
$.ajax({
url: '/api/courses/42',
dataType: 'json',
})
.done(function (course) {
$('#course-title').text(course.title);
$('#course-description').text(course.description);
})
.fail(function (xhr) {
$('#error-message').text('Could not load course: ' + xhr.status);
});
$.ajax() returns a jqXHR object, which behaves like a Promise — .done(), .fail(), and .always() are jQuery's equivalents of a native Promise's .then(), .catch(), and .finally().
A real form example
<form id="signup-form">
<input type="email" name="email" required>
<button type="submit">Subscribe</button>
</form>
<p id="signup-status"></p>
$('#signup-form').on('submit', function (event) {
event.preventDefault();
const email = $(this).find('input[name="email"]').val();
$.ajax({
url: '/api/subscribe',
method: 'POST',
data: { email: email },
dataType: 'json',
})
.done(function (response) {
$('#signup-status').text('Subscribed! Check your inbox.');
})
.fail(function (xhr) {
$('#signup-status').text('Something went wrong. Please try again.');
});
});
Comparing to the native fetch() API
Modern browsers provide fetch() natively — no library required — and it's the standard choice for new code today:
// jQuery
$.ajax({ url: '/api/users', dataType: 'json' })
.done(data => console.log(data))
.fail(err => console.error(err));
// Native fetch
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
$.ajax() |
fetch() |
|
|---|---|---|
| Requires a library | Yes (jQuery) | No — built into every modern browser |
| Automatically rejects on HTTP error status (404, 500) | Yes | No — only rejects on a network failure; you must check response.ok yourself |
| JSON parsing | dataType: 'json' does it automatically |
Explicit extra step: response.json() |
| Return type | jqXHR (Promise-like, jQuery-specific) | A native Promise |
| Progress events, request abort | Built in (xhr events, .abort()) |
Needs AbortController for cancellation; no built-in upload progress |
A commonly-missed fetch() gotcha, precisely because $.ajax() behaves differently here:
fetch('/api/might-404')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`); // fetch does NOT do this automatically
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('Request failed:', err));
For a project already using jQuery for DOM manipulation, $.ajax() remains a perfectly reasonable, consistent choice. For a brand-new project with no other jQuery dependency, fetch() (or a small wrapper library) avoids pulling in jQuery just for HTTP requests.
Common mistakes
- Assuming
fetch()rejects on a 404 or 500 response the way$.ajax()'s.fail()does — it doesn't; you must explicitly checkresponse.okand throw yourself. - Forgetting
dataType: 'json'(or an equivalent serverContent-Typeheader) and then manually callingJSON.parse()on data jQuery would have parsed automatically. - Not calling
event.preventDefault()before making an AJAX request from a form'ssubmithandler, causing the browser to also perform its own default navigation. - Adding jQuery to a project solely for
$.ajax()when the project has no other jQuery usage — nativefetch()covers the same need with zero dependencies.