Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 56 ยท AJAX

Real-World AJAX Patterns

Learn the AJAX patterns used in real jQuery apps: loading states, error handling with retries, safe JSON rendering, pagination, debounced live search and CSRF headers.

Knowing $.ajax() is one thing; building a screen that feels reliable is another. Real users have slow connections, servers fail, results arrive out of order and pages receive data that nobody sanitized. The same handful of patterns solves these problems in almost every project, and once you recognize them you will write them quickly and correctly.

This lesson collects those patterns: showing progress, handling errors and retrying, rendering JSON without opening a security hole, paging through results, searching while the user types, and sending the headers that servers expect. It builds on AJAX basics, the shorthand methods and promises.

Six patterns you will reuse

Loading state Show progress, always clear it.
Retry Try again when a request fails.
Safe render Use .text(), never raw HTML.
Live search Debounce and ignore stale replies.
1 / 2

A stand-in server for the examples

The examples on this page run in a sandbox that cannot reach a real API, so each one uses a small function that behaves like a server: it returns a promise and resolves or rejects it after a delay. Everything after it, .done(), .fail(), .always(), is exactly what you would write against the object returned by $.ajax(). With a real endpoint you would delete the stand-in and call $.ajax({ url: "/api/..." }) instead.

Pattern 1: a loading state that always clears

Show something as soon as the request starts and remove it when the request ends, whether it succeeded or failed. .always() exists for exactly this. If you clear the spinner only in .done(), a failed request leaves it spinning forever.

Also disable the button that triggered the request. Otherwise an impatient user clicks five times and you send five requests.

JavaScript
$button.prop("disabled", true);
$status.text("Loading...");

$.ajax({ url: "/api/report" })
  .done(renderReport)
  .fail(showError)
  .always(function () {
    $button.prop("disabled", false);
    $status.text("");
  });

Pattern 2: handling errors and retrying

Treat failure as a normal outcome. The .fail() callback receives the jqXHR object, a text status ("timeout", "error", "abort", "parsererror") and the error message. Use them to tell the user something useful: a timeout deserves "The server is slow, try again", while a 404 deserves "That item no longer exists".

A retry wraps the request in a function that calls itself with a counter. Wait a little longer before every attempt (exponential backoff) so you do not hammer a server that is already struggling. Retry only requests that are safe to repeat, such as GET; blindly retrying a POST that charges a card is a bug.

Retry with a growing delay

The important design choice is that requestWithRetry returns a promise that settles only after the last attempt. The caller does not need to know that retries happen; it simply waits for .done() or .fail().

Pattern 3: rendering JSON without opening a security hole

JSON from a server is data, and data can contain anything: <, &, even a <script> tag that an attacker saved in their username. If you build rows with string concatenation and .html(), that markup becomes part of your page, and this is called cross-site scripting (XSS).

The safe rule is simple: create elements, then fill them with .text() or .attr(). Both methods treat the value as plain text, so markup is displayed instead of executed.

JavaScript
// Dangerous: the name is parsed as HTML
$list.append("<li>" + user.name + "</li>");

// Safe: the name is only ever text
$("<li>").text(user.name).appendTo($list);

The same applies to attributes. $("<a>").attr("href", user.site) is safe from tag injection, but a value such as javascript:alert(1) is still a dangerous link. If a URL comes from users, check that it starts with https:// or http:// before using it.

Pattern 4: pagination and "load more"

Never fetch everything at once. Ask the server for one page, show it, and remember the next page number. A "Load more" button is the simplest interface: each click appends the next page, and the button disappears when the server says there is nothing left. The same function powers infinite scroll, which just calls it from a scroll handler (see common events for throttling) instead of a click.

Two details matter. Keep a flag such as loading so a fast double click does not request the same page twice, and let the response tell you whether more pages exist (hasMore, a next link, or a total count) instead of guessing.

Load more with a loading flag

Notice that the post text contains <b>&</b>. Because each item is created with .text(), the tags show up literally instead of making text bold.

Searching while the user types is pleasant but expensive if every keystroke sends a request. Debouncing waits until the user pauses for a moment (typically 250-400 ms) and only then sends one request. In jQuery you build it with setTimeout and clearTimeout.

There is a second problem that debouncing does not solve: responses can arrive out of order. If the request for "ja" is slow and the request for "jav" is fast, the old answer would overwrite the newer one. Fix it by keeping the latest request and aborting the previous one with jqXHR.abort(), or by tagging each request with an id and ignoring replies that are not the newest. The stand-in below uses the id approach because it works with any promise.

Pattern 6: CSRF tokens and global headers

Browsers attach cookies to requests automatically, which means another site could trick a logged-in user into sending a state-changing request to yours. Frameworks defend against this with a CSRF token that the page must send back in a header. Rather than adding it to every call, register it once with $.ajaxSetup() (or a beforeSend in a prefilter, see promises and Ajax events):

JavaScript
var token = $('meta[name="csrf-token"]').attr("content");

$.ajaxSetup({
  headers: { "X-CSRF-TOKEN": token }
});

Only send the token to your own origin. A global setup also attaches it to requests that go to other sites, which would leak it, so for cross-origin calls set the headers on that single request instead.

Cross-origin requests and JSONP

Browsers block pages from reading responses from another origin unless that server opts in with CORS headers (Access-Control-Allow-Origin). If the API sends them, a normal $.ajax() just works. If it does not, the old workaround was JSONP (dataType: "jsonp"), which injects a <script> tag. JSONP only supports GET, cannot report HTTP errors properly and runs the remote code with full access to your page, so treat it as a legacy technique. Ask the API owner to enable CORS, or call it through your own server.

Debounced live search that ignores stale replies

Type ja and keep going to java quickly. The slow answer for ja arrives late, but its id is no longer the latest, so it is dropped.

Recipes: a small HTTP library, nested JSON and file uploads

Three jobs come up in almost every project. Write them once, as a tiny wrapper, and the rest of the code stays short.

A wrapper over $.ajax. Instead of repeating dataType, contentType and error handling in every call, make one function and derive the verbs from it. Because $.ajax() already returns a promise, the wrapper returns that promise and callers use .then() or .done().

Posting nested JSON. Form encoding flattens data (user[name]=Ada), which is awkward for nested objects and arrays. Instead, send a JSON string: use JSON.stringify(data), set contentType: "application/json", and leave processData alone (it only touches non-string data). The server reads the body as JSON.

Uploading a file. Use a FormData object. Set processData: false so jQuery does not try to turn it into a query string, and contentType: false so the browser writes the correct multipart/form-data header with its boundary. If you set the header by hand the boundary is missing and the upload fails. You can also report progress with an xhr option that returns a customised XMLHttpRequest.

A wrapper, a JSON post and a FormData upload

The same wrapper handles all three. Notice that JSON goes out with contentType: "application/json" and the file goes out with contentType: false; those two settings are the whole difference. Put authentication headers, CSRF tokens and a global error message inside request() once (see Pattern 6 above) and every call benefits. If you later switch to fetch(), only the body of request() needs to change, which is the best argument for keeping the wrapper.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a loading indicator usually removed inside .always() instead of .done()?

    .always() runs after both success and failure. Clearing the indicator only on success would leave it spinning after an error.
  2. 2. Which line renders a username from a server safely?

    .text() treats the value as plain text, so any markup in the name is displayed rather than executed. The other lines parse the name as HTML.
  3. 3. What does debouncing a live search accomplish?

    A debounced handler restarts a timer on each keystroke and only sends the request when the timer finally expires.
  4. 4. A slow reply for an older search arrives after the reply for a newer one. How do you avoid showing the wrong results?

    Tagging each request with an id (or aborting the previous jqXHR) guarantees that only the newest search can update the page.
  5. 5. Why should you be careful with retries?

    Retry requests that are safe to repeat, like GET. Repeating a POST that creates or charges something can do it twice.

Summary

  • Show a loading state when a request starts and clear it in .always(); disable the trigger button to prevent duplicate requests.
  • Handle failure deliberately: use the status and error arguments of .fail(), and retry only safe requests, with a growing delay.
  • Render server data with $("<tag>").text(value); never concatenate it into HTML strings.
  • Paginate with a page counter, a loading flag and a "has more" signal from the server.
  • Debounce live search and ignore stale replies by request id or by aborting the previous request.
  • Register CSRF headers once with $.ajaxSetup(), send them to your own origin only, and prefer CORS over JSONP.

Next, move from data loading to user input in Working with Form Controls.