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

← All jQuery questions