← Back to jQuery Course | Chapter 9: AJAX Basics | Lesson 1 of 7

Introduction to AJAX

AJAX lets a page request data from a server without reloading the whole page. jQuery makes AJAX tasks easier.
Syntax
javascript
$.ajax({
  url: "url",
  method: "GET",
  success: function(data) {
    // use data
  },
  error: function() {
    // handle failure
  }
});

What is AJAX?

AJAX lets a page request data from a server in the background without a full page reload; jQuery wraps the browser's raw AJAX API in a simpler, more consistent one. This is what makes features like live search or infinite scroll possible without navigating away.

Example: What is AJAX?

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <button id="btn">Load</button>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    function init() {
      $("#btn").on("click", function() {
        $.ajax({url: "data.php", success: function(data) {
          $("#output").append($("<div>").text("Received: " + JSON.stringify(data)));
        }});
      });
    }
    init();

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
      init();
    });
  </script>
</body>
</html>

AJAX Method

The $.ajax() method accepts a configuration object with options such as url, method, data, success, and error, giving you full control over exactly how the request is made. It's the most flexible AJAX method jQuery provides, underlying the shorthand methods like get() and post().

Example: AJAX Method

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "data.php",
        method: "GET",
        success: function(data) { $("#output").append($("<div>").text(JSON.stringify(data))); },
        error: function() { $("#output").append($("<div>").text("Request failed")); }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

Handling Returned Data

A successful request passes its returned data to the success callback, where you can use it to update the page -- inserting it into the DOM, filling a table, or updating a counter. What that data looks like depends entirely on what the server sends back.

Example: Handling Returned Data

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <ul id="list"></ul>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();
    $(document).ajaxError(function(event, xhr, settings) {
      $("#output").append($("<div>").text("Request failed: " + settings.url));
    });

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({url: "data.php", success: function(data) {
        $("#list").append("<li>" + data.message + "</li>");
      }});
    });

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

AJAX Error Handling

Network requests can fail for many reasons -- a dropped connection, a server error, a bad URL -- so the error callback lets you show a friendly message instead of leaving the page silently broken. Handling this case is just as important as handling success.

Example: AJAX Error Handling

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
  </style>
</head>
<body>
  <button id="runBtn">Run</button>
  <button id="resetBtn">Reset</button>
  <div id="output"></div>
  <script>

    $("#runBtn").click(function() {
      $("#output").empty();
      $("#output").append($("<div>").text("Sending request..."));
      $.ajax({
        url: "data.php",
        success: function(data) { $("#output").append($("<div>").text(JSON.stringify(data))); },
        error: function() { $("#output").append($("<div>").text("Something went wrong, please try again")); }
      });
    });

    $("#resetBtn").click(function() {
      jQuery(document).off();
      $("#output").empty();
    });
  </script>
</body>
</html>

AJAX in a Small Project

AJAX is useful for small interactive pages where loading everything up front would be wasteful, like fetching extra details only when the user clicks a 'show more' button. This keeps the initial page load light while still allowing rich, on-demand interactivity.

Example: AJAX in a Small Project

javascript
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>
    button { padding:6px 14px; margin:4px; background:#2c6aa0; color:white; border:none; border-radius:4px; cursor:pointer; }
    #resetBtn { background:white; color:#2c6aa0; border:1px solid #2c6aa0; }
    #output { margin-top:10px; padding:8px; border:1px solid #ccc; border-radius:4px; background:#f7f7f7; font-family:monospace; min-height:24px; }
    #demo :where(p, div, span, li, h1, h2, h3, h4, td, th, blockquote, label, section, article, aside) { border:1px solid #4a7fb5; background:#eaf2fb; padding:6px 10px; margin:4px 0; border-radius:4px; }
    #demo :where(ul, ol) { border:1px dashed #888; background:#fafafa; padding:8px 8px 8px 32px; margin:6px 0; }
    #demo :where(table) { border-collapse:collapse; }
    #demo :where(td, th) { border-radius:0; }
    #demo :where(input, select, textarea) { margin:4px 0; }
  </style>
</head>
<body>
  <button id="resetBtn">Reset</button>
  <section id="demo">
    <button id="showMore">Show More</button>
    <div id="details"></div>

  </section>
  <div id="output"></div>
  <script>
    var original = $("#demo").html();

    function init() {
      $("#showMore").on("click", function() {
        $.ajax({url: "data.php", success: function(data) {
          $("#details").text(data.message);
        }});
      });
    }
    init();

    $("#resetBtn").click(function() {
      $("#demo").html(original);
      $("#output").empty();
      init();
    });
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting $.ajax() to return the data directly like const d = $.ajax(...), when the request is asynchronous and the data only arrives in success or .done().
  2. Using code that depends on the response right after the $.ajax() call, which runs before the response arrives.
  3. Forgetting an error callback so failed requests such as a bad url fail silently and the user sees nothing.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.