jQuery ajaxPrefilter() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Ajax

Definition

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.

Syntax

Start with these common calls. Keep them short and readable.

jQuery
$.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";
CallWhat it does
dataTypesSpace-separated filter, e.g. "json script"
optionsMerged settings — safe to mutate for this request
originalOptionsCaller input without ajaxSetup defaults
jqXHRRequest object — store / abort when needed

Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.

Parameters

ParameterDescription
Step 1Call $.ajaxPrefilter(handler) (optionally with a dataTypes string).
Step 2Inside the handler, read or mutate options; inspect originalOptions when you need the caller’s raw input.
Step 3Use jqXHR for patterns like abort-on-retry.

Return Value

Return ValueDescription
Value / undefinedGetters usually return a value from the first matched element, or undefined when nothing applies.

jQuery Examples

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.

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.

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.

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() Method tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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