jQuery ajaxPrefilter() Method

Beginner
8 min read
Updated: Oct 2026
5 examples
Live preview

What Is ajaxPrefilter()?

jQuery.ajaxPrefilter([dataTypes], handler) (since jQuery 1.5) registers a hook that runs before each Ajax request is sent and before options are fully processed. Use it to tweak settings, handle custom flags, or redirect a request to another dataType.

Remember
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  // mutate options before the request is sent
});

// Optional: only for matching dataTypes
$.ajaxPrefilter("json script", function (options) { /* ... */ });

// Return a dataType string to redirect processing
// return "script";
NeedUse
Per-request option logic$.ajaxPrefilter(handler)
Static global defaults$.ajaxSetup() (use carefully)
Last-moment XHR / cancelbeforeSend on one call
Core request API$.ajax()
Custom transport$.ajaxTransport()

How to Use ajaxPrefilter()

Register once at startup, then every jQuery Ajax call can inherit the behavior.

  1. Call $.ajaxPrefilter(handler) (optionally with a dataTypes string).
  2. Inside the handler, read or mutate options; inspect originalOptions when you need the caller’s raw input.
  3. Use jqXHR for patterns like abort-on-retry.
  4. Optionally return "json" (or another dataType) to redirect processing.
  5. Make requests with $.ajax(), $.get(), $.post(), or .load() as usual.
PieceRequired?Role
dataTypesOptionalSpace-separated filter, e.g. "json script"
optionsYes (arg)Merged settings — safe to mutate for this request
originalOptionsYes (arg)Caller input without ajaxSetup defaults
jqXHRYes (arg)Request object — store / abort when needed

Pseudocode

Pseudocode
register ajaxPrefilter(optional dataTypes, handler)

when $.ajax() / $.get() / $.post() / .load() starts:
    merge ajaxSetup defaults into options
    for each matching prefilter (by dataTypes, if any):
        call handler(options, originalOptions, jqXHR)
        if handler returns a dataType string:
            set request dataType to that value
            run dataType-specific prefilters too
    run beforeSend (if set)
    send via transport

Cheat Sheet

Keep these facts handy while wiring global Ajax hooks.

TopicDetail
Syntax$.ajaxPrefilter( [dataTypes], handler )
Returnsundefined
SincejQuery 1.5
Handlerfunction(options, originalOptions, jqXHR)
ScopeAll Ajax, or matching dataTypes only
Redirectreturn "script" (or another dataType)
vs ajaxSetupPrefilter = per-request logic; setup = static defaults
vs beforeSendPrefilter runs earlier; can change options / dataType

Live Preview

A registered prefilter adds a custom header, then you run a real $.get() and watch the log.

Live demo uses a public JSON API. Needs network access.

Result
Ready — pick an action and click Run.

jQuery Examples

Short, copy-ready snippets based on the official jQuery API patterns. Use Try It Yourself for a live editor.

Example 1 — Basic Registration

Log the URL and add a custom header before every Ajax request.

jQuery
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  console.log("Ajax prefilter:", options.url);

  options.headers = $.extend({}, options.headers, {
    "X-App-Client": "CodeToFun-Demo"
  });
});

$("#load").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    dataType: "json"
  }).done(function (data) {
    $("#result").text("Loaded: " + data.title);
  });
});
Try It Yourself

How It Works

  1. Register. $.ajaxPrefilter(fn) stores the handler once.
  2. Click. $.ajax() starts a JSON request.
  3. Mutate. The handler updates options.headers for this call.
  4. Send. The transport includes the header; .done() shows the title.

Example 2 — Official abortOnRetry Pattern

Abort an in-flight request to the same URL when a custom flag is set.

jQuery
var currentRequests = {};

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  if (options.abortOnRetry) {
    if (currentRequests[options.url]) {
      currentRequests[options.url].abort();
    }
    currentRequests[options.url] = jqXHR;
  }
});

$("#search").on("input", function () {
  var q = $(this).val();
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts?q=" + encodeURIComponent(q),
    abortOnRetry: true,
    dataType: "json"
  }).done(function (posts) {
    $("#count").text(posts.length + " results");
  });
});
Try It Yourself

How It Works

  1. Custom flag. abortOnRetry is ignored by the transport — your prefilter reads it.
  2. Store. Keep the current jqXHR keyed by options.url.
  3. Abort. A new call to the same URL aborts the previous one.
  4. Opt in. Only requests that set the flag are affected.

Example 3 — Scope by dataTypes: "json"

Run the handler only for JSON requests — HTML or script calls skip it.

jQuery
$.ajaxPrefilter("json", function (options) {
  console.log("JSON prefilter:", options.url);
  options.headers = $.extend({}, options.headers, {
    "Accept": "application/json"
  });
});

$("#load-user").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/users/1",
    dataType: "json"
  }).done(function (user) {
    $("#name").text(user.name);
  });
});

$("#load-html").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    dataType: "html"
  }).done(function () {
    $("#name").text("HTML request — JSON prefilter skipped");
  });
});
Try It Yourself

How It Works

  1. Filter. The first argument limits the handler to dataType: "json".
  2. Match. The user request runs the prefilter and sets Accept.
  3. Skip. The HTML request never enters this handler.
  4. Multi. Use "json script" to match either type.

Example 4 — Force cache: false on GET

Bust browser caches for GET without adding cache: false to every call.

jQuery
$.ajaxPrefilter(function (options) {
  var method = (options.type || options.method || "GET").toUpperCase();

  if (method === "GET" && options.cache !== true) {
    options.cache = false;
  }
});

$("#refresh").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1"
  }).done(function (post) {
    $("#log").text(
      "Fetched at " + new Date().toLocaleTimeString() + " — " + post.title
    );
  });
});
Try It Yourself

How It Works

  1. Detect GET. Read type / method (default GET).
  2. Set. Assign cache: false unless the caller opted into true.
  3. Bust. jQuery appends a _=timestamp query param on GET.
  4. Careful. Gate or remove this in production if you rely on CDN caching.

Example 5 — Add an Authorization Header

Attach a bearer token to every API call by mutating options.headers.

jQuery
var apiToken = "demo-token-abc123";

$.ajaxPrefilter(function (options) {
  options.headers = $.extend({}, options.headers, {
    "Authorization": "Bearer " + apiToken
  });
});

$("#fetch").on("click", function () {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/users/1",
    dataType: "json"
  }).done(function (user) {
    $("#status").text("Authorized fetch OK: " + user.email);
  });
});
Try It Yourself

How It Works

  1. Token. Keep the secret outside the click handler.
  2. Merge. Extend options.headers so existing headers are kept.
  3. Send. Every later Ajax call gets the Bearer header automatically.
  4. Alt. Wrap options.beforeSend if you need the raw XHR or cancel with false.

Edge Cases & Pitfalls

Check these before shipping global Ajax prefilters.

scope

Affects every matching Ajax call

Including third-party plugins that use jQuery Ajax. Prefer dataTypes filters or custom flags so you do not surprise unrelated traffic.

options

options vs originalOptions

Mutate options for the request. originalOptions is the pristine caller input — do not treat them as the same object.

order

Runs after ajaxSetup, before beforeSend

Defaults from $.ajaxSetup() are already merged. beforeSend still runs later and can cancel with false.

return

Returning a dataType redirects

return "script" changes transport and runs script-specific prefilters. Only return a string when you mean to redirect.

fetch

Does not wrap fetch() or axios

Prefilters only see jQuery Ajax ($.ajax and shorthands). Native fetch() never enters them.

Browser Support

jQuery.ajaxPrefilter() has been part of jQuery since 1.5. It works in every browser that runs your loaded jQuery version — no separate browser feature flag.

✓ Stable · jQuery 1.5+

jQuery.ajaxPrefilter()

Supported across jQuery 1.5+, 2.x, and 3.x. Prefer a current jQuery 3.x build for modern projects. Requires jQuery Ajax — fetch() and axios do not use prefilters.

100% With jQuery Ajax
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
ajaxPrefilter Universal

Bottom line: Safe for everyday apps. Register once, filter by dataTypes when possible, and keep handlers light.

Performance Notes

ApproachCostBest for
One light prefilterCheapHeaders, flags, small option tweaks
dataTypes-scoped prefilterCheapJSON-only or script-only logic
Heavy work in every prefilterExpensiveAvoid — keep handlers tiny

Prefilters run on every matching request. Keep them synchronous and small — no DOM thrashing or large JSON parsing inside the handler.

Key Takeaways

  • Role: global hook before each jQuery Ajax request is sent.
  • Args: (options, originalOptions, jqXHR) — mutate options.
  • Scope: optional dataTypes; return "script" redirects.
  • Choose: prefilter for logic; ajaxSetup for static defaults; beforeSend for last-moment XHR.

One line: $.ajaxPrefilter() lets you change Ajax options (or abort / redirect) before every jQuery request is sent.

Frequently Asked Questions

jQuery.ajaxPrefilter() registers a handler that runs before each Ajax request is sent and before jQuery finishes processing the settings. Use it to modify options, handle custom flags (like abortOnRetry), scope by dataTypes, or return a dataType string. Every $.ajax(), $.get(), $.post(), and .load() call passes through registered prefilters.
options is the merged settings object jQuery will use — including defaults from $.ajaxSetup() and ajaxSettings. originalOptions is exactly what you passed to $.ajax() (or what a shorthand built), without those merged defaults. Compare them when you need to know whether a value came from the caller or from global setup.
When you call $.ajaxPrefilter("json script", handler), the handler runs only for matching dataTypes. Omit dataTypes to run on every Ajax request. Space-separate multiple types in one string.
If your prefilter returns a string such as "script" or "json", jQuery treats the request as that dataType. That affects transport selection and runs prefilters registered for that dataType.
$.ajaxSetup() sets static default values merged into every request. $.ajaxPrefilter() runs a function per request with access to options, originalOptions, and jqXHR — better for conditional logic, aborting duplicates, or rewriting URLs. Prefilters run after ajaxSetup merge.
Prefilters run earlier, before beforeSend. They can change options for the whole pipeline and optionally return a dataType. beforeSend runs once per request just before send, receives the XHR, and can return false to cancel. Use prefilters for cross-cutting option changes; use beforeSend for last-moment XHR tweaks or cancel.

Next: ajaxSetup() Method

Learn static Ajax defaults — and why jQuery recommends using them carefully.

ajaxSetup() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful