SyntaxStudy
Sign Up
jQuery jQuery AJAX Introduction
jQuery Beginner 5 min read

jQuery AJAX Introduction

AJAX (Asynchronous JavaScript and XML) allows web pages to communicate with a server in the background without reloading. jQuery wraps the browser's XMLHttpRequest and, in modern browsers, fetch into a single unified API that handles all the common boilerplate for you.

The $.ajax() Method

$.ajax() is the low-level foundation of all jQuery HTTP requests. It accepts a settings object where you specify the URL, HTTP method, data to send, expected response format, and callback functions for success, error, and completion.

Why Use jQuery AJAX?

Beyond simpler syntax, jQuery AJAX provides cross-browser consistency, automatic JSON serialisation and parsing, a global event system for loading indicators, and promise-based chaining through the jqXHR object it returns.

  • $.ajax() — full-featured, all options
  • $.get() — shorthand GET request
  • $.post() — shorthand POST request
  • $.getJSON() — GET and parse JSON automatically
  • .load() — load HTML into an element

Every jQuery AJAX method returns a jqXHR object that implements the Promise interface, so you can chain .then(), .done(), .fail(), and .always() callbacks.

Example
// Basic $.ajax() call
$.ajax({
    url    : '/api/users',
    method : 'GET',
    success: function (data) {
        console.log('Users:', data);
    },
    error  : function (xhr, status, err) {
        console.error('Error:', err);
    }
});

// Promise-style chaining
$.ajax({ url: '/api/posts', method: 'GET' })
  .done(function (data)   { renderPosts(data); })
  .fail(function (xhr)    { showError(xhr.status); })
  .always(function ()     { hideSpinner(); });
Pro Tip

Use .done()/.fail()/.always() chaining on jqXHR objects instead of inline callbacks for cleaner code.