jQuery interview question · Most asked
How do you make AJAX requests with jQuery?
Summary
$.ajax({...}) is the general method; shorthands include $.get, $.post and $.getJSON. They return a jqXHR object that implements the Promise interface, so you chain .done(), .fail(), .always() or .then().
Longer Answer
$.ajax({
url: "/api/orders",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ items }),
dataType: "json",
timeout: 10000,
})
.done((order) => showConfirmation(order))
.fail((xhr) => showError(xhr.status, xhr.responseJSON))
.always(() => $submit.prop("disabled", false));
Notes: by default data objects are form-encoded, so set contentType and stringify for JSON APIs; set a timeout; handle failures visibly; and send the CSRF token for state-changing requests. The success/error callbacks still work, but the promise style composes better.
Key Points
- $.ajax and shorthands.
- jqXHR is promise-like: done/fail/always/then.
- JSON needs contentType + stringify.
- Timeouts, errors, CSRF.
More most-asked jQuery questions
- What is the difference between .html() and .text(), and why does it matter for security?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- What is event delegation, and why is it useful?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What are jQuery Deferreds, and how do you wait for several requests?
- What is the difference between .attr() and .prop()?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?