Home Module 16 AJAX with jQuery

Introduction

AJAX (Asynchronous JavaScript and XML) lets a page request data from a server in the background and update part of the UI without a full reload. jQuery wrapped the clunky XMLHttpRequest API into a few clean methods that worked the same in every browser — a major reason for its popularity.

You learned the modern equivalent, fetch(), in module 14. jQuery's AJAX methods do the same job with a slightly different API you'll meet in older codebases.

Theory

The methods

  • $.ajax(options) — the full-control method; configure URL, method, data, headers, and callbacks.
  • $.get(url, cb) — shorthand for a GET request.
  • $.post(url, data, cb) — shorthand for a POST request.
  • $.getJSON(url, cb) — GET that automatically parses a JSON response.

Handling responses

Modern jQuery AJAX returns a promise-like object, so you chain handlers:

$.getJSON('https://api.example.com/users')
  .done(function (data) { /* success */ })
  .fail(function (err)  { /* error */ })
  .always(function ()   { /* runs either way */ });

Or with $.ajax:

$.ajax({
  url: 'https://api.example.com/users',
  method: 'GET',
  dataType: 'json'
}).done(handleSuccess).fail(handleError);
Security: render server data with .text() (escaped), not .html(), unless you fully trust and sanitize the source. API responses can contain attacker-controlled strings.

Real World Example

Click below to fetch a post from the public JSONPlaceholder API. The title and body are inserted with .text(), so any markup in the response is shown as literal text — never executed:

$('#loadBtn').on('click', function () {
  $.getJSON('https://jsonplaceholder.typicode.com/posts/1')
    .done(function (post) {
      $('#postTitle').text(post.title);   // .text() — XSS safe
      $('#postBody').text(post.body);
    })
    .fail(function () {
      $('#postTitle').text('Request failed.');
    });
});

No data yet.

Click the button to fetch from the API.

Common Mistakes

  • Expecting synchronous results. AJAX is asynchronous — read the data inside the callback, not on the line after the call.
  • Ignoring errors. Always attach .fail() (or an error callback) so failures don't fail silently.
  • Rendering responses with .html(). Untrusted API data can carry script payloads — use .text().
  • CORS surprises. Browsers block cross-origin requests unless the server sends the right headers.

Best Practices

  • Use $.getJSON for simple JSON GETs; reach for $.ajax when you need headers, methods, or fine control.
  • Always handle the error case and show the user a clear message.
  • Show a loading indicator while the request is in flight; clear it in .always().
  • For new code, consider native fetch() — but know the jQuery equivalents for maintaining legacy apps.

Practice Exercise

  1. Use $.getJSON to fetch https://jsonplaceholder.typicode.com/users.
  2. In .done(), loop the array and append each user's name to a list with .text().
  3. Add a .fail() handler that shows an error message.
  4. Add a loading message that clears in .always().

Assignment

Build a small "user lookup" tool:

  1. An input for a user id (1–10) and a "Fetch" button.
  2. On click, call $.getJSON('https://jsonplaceholder.typicode.com/users/' + id).
  3. Render the user's name, email, and city — each set with .text().
  4. Handle invalid ids and network errors gracefully with .fail().
Security reminder: every field you display comes from the API — set it with .text(), never .html().

Interview Questions

  • What is AJAX? — A technique for exchanging data with a server asynchronously so the page updates without a full reload.
  • What's the difference between $.get and $.getJSON?$.getJSON automatically parses the response as JSON; $.get returns it as-is (or per dataType).
  • How do you handle a failed request? — Attach .fail() (or an error callback in $.ajax).
  • How do you safely display API data? — Use .text() so the data is escaped, guarding against XSS.
  • What's the modern vanilla equivalent? — The fetch() API with promises / async-await.

Additional Resources

  • api.jquery.com/jQuery.ajax — the $.ajax reference
  • api.jquery.com/jQuery.getJSON — the $.getJSON reference
  • jsonplaceholder.typicode.com — a free fake REST API for testing