AJAX Overview

Fetch data from a server and update the page without reloading.

AJAX (Asynchronous JavaScript And XML) lets your page request data in the background and update itself — no full reload. jQuery wraps the browser's request machinery in simple methods.

AJAX request and response flowBrowser$.get(...)Server/api/data1. HTTP request (async)2. JSON / HTML response3. done() callback updates the page — no reload
AJAX fetches data in the background and updates part of the page without a full reload.

The jQuery AJAX toolkit

  • .load() — drop HTML from a URL into an element.
  • $.get() / $.post() — simple GET and POST requests.
  • $.getJSON() — fetch and parse JSON.
  • $.ajax() — the full-control method behind them all.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A social feed loads new posts by polling the server every 30 seconds via AJAX without a full page refresh.
  • An e-commerce product page updates the stock count live by sending an AJAX request when the user selects a size.
  • A live chat app posts each new message to the server via AJAX and appends the response to the conversation window.

More examples

Basic AJAX GET with jQuery

$.ajax() sends the request asynchronously; the success callback receives the parsed response without reloading.

Example Β· html
<button id="fetch">Fetch data</button>
<div id="result"></div>
<script>
$(function () {
  $("#fetch").click(function () {
    $.ajax({
      url: "/api/hello",
      method: "GET",
      success: function (data) {
        $("#result").text(data.message);
      }
    });
  });
});
</script>

Show loading state during request

The spinner is shown before the request and hidden inside the callback to give the user visual feedback.

Example Β· html
<button id="load">Load</button>
<div id="spinner" style="display:none;">Loading...</div>
<div id="out"></div>
<script>
$(function () {
  $("#load").click(function () {
    $("#spinner").show();
    $.get("/api/items", function (data) {
      $("#spinner").hide();
      $("#out").text(JSON.stringify(data));
    });
  });
});
</script>

Handle AJAX errors gracefully

The error callback receives the XHR object and status string so the UI can display a meaningful failure message.

Example Β· html
<button id="req">Request</button>
<p id="msg"></p>
<script>
$(function () {
  $("#req").click(function () {
    $.ajax({
      url: "/api/data",
      success: function (d) {
        $("#msg").text("OK: " + d.value);
      },
      error: function (xhr, status) {
        $("#msg").text("Error " + xhr.status + ": " + status);
      }
    });
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.