jQuery AJAX & Misc
jQuery's AJAX methods let a page request data from a server and update part of the page without reloading. They wrap the browser's XMLHttpRequest in a simpler interface and return objects that behave like promises. You will meet them in many existing websites and admin panels. This lesson also covers a few utility features, such as $.each(), .data() and .serialize(), that often appear alongside AJAX code.
The main AJAX methods
$.ajax(options)is the full method; every other helper calls it.$.get(url, data)and$.post(url, data)are shortcuts for the common cases.$.getJSON(url)sends a GET and parses the response as JSON.$(selector).load(url)fetches HTML and inserts it directly into the selected element.
$('#search-form').on('submit', function (event) {
event.preventDefault();
const $results = $('#results').text('Searching...');
$.ajax({
url: '/api/courses',
method: 'GET',
data: $(this).serialize(), // "q=react&level=beginner"
dataType: 'json',
timeout: 8000
})
.done(function (courses) {
$results.empty();
$.each(courses, function (index, course) {
$('<li>')
.text(course.title)
.data('courseId', course.id)
.appendTo($results);
});
})
.fail(function (jqXHR, textStatus) {
$results.text('Could not load results (' + textStatus + ').');
})
.always(function () {
$('#spinner').hide();
});
});
$('#results').on('click', 'li', function () {
console.log('Clicked course', $(this).data('courseId'));
});
Handling success and failure
The object returned by jQuery AJAX methods is a jqXHR, which offers .done(), .fail() and .always(). Since jQuery 3 it is also compatible with standard promises, so .then() and await work. Unlike fetch(), jQuery treats HTTP error statuses such as 404 or 500 as failures and calls .fail(), with jqXHR.status holding the code. The old success, error and complete callbacks still work as options, but the chained methods are clearer.
Sending data
The data option accepts an object or a string. For GET it is added to the URL as a query string; for POST it is form-encoded by default. To send JSON instead, set contentType: 'application/json' and pass JSON.stringify(payload) as the data. .serialize() turns a form's named fields into an encoded string, and .serializeArray() gives an array of name/value pairs.
Handy extras
$.each() loops over arrays or objects, passing index and value. .data() stores values on elements without putting them in attributes and reads data-* attributes. $.extend() merges objects, useful for default settings. $.noConflict() releases the $ name if another library uses it.
Global AJAX events can show one loading indicator for every request on the page: $(document).on('ajaxStart', ...) fires when the first request begins and ajaxStop when the last one finishes.
Pitfalls with jQuery AJAX
Requests are asynchronous, so code placed after $.ajax() runs before the response arrives. Assigning the result to a variable outside the callback and using it on the next line gives undefined. Do the work inside .done(), or await the request. Avoid the deprecated async: false option, which freezes the page.
Another frequent problem is building results with .html() and server text, which can inject scripts. Use .text(), as the example does, for any data you did not write yourself. Also note that the slim build of jQuery leaves out AJAX entirely, so $.ajax will be undefined if you loaded jquery.slim.min.js.
Summary
Use $.ajax or its shortcuts, handle results with .done, .fail and .always, insert server data with .text(), and keep dependent code inside the callbacks.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.