jQuery ajaxSetup() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Core Ajax API

What You’ll Learn

$.ajaxSetup() configures default Ajax options merged into every future $.ajax(), $.get(), $.post(), and .load() call. This tutorial covers merge behavior, per-call overrides, jQuery’s official “not recommended” warning, why global success/error callbacks belong on $(document).on() instead, how setup fits before $.ajaxPrefilter() in the pipeline, and safer alternatives like explicit options or a small wrapper plugin.

01

Global defaults

Merge into all Ajax

02

Per-call override

Caller wins

03

Not recommended

Plugin risk

04

PlainObject return

ajaxSettings merge

05

Global events

ajaxSuccess on doc

06

Since 1.1

Core Ajax API

Introduction

Before your app has dozens of $.ajax() calls, setting the same url prefix, dataType, or HTTP method on every line feels repetitive. jQuery offers jQuery.ajaxSetup( options ) to define those defaults once. Every subsequent Ajax call — including shorthands like $.get(), $.post(), and .load() — merges your setup object into its settings until the next $.ajaxSetup() invocation.

⚠️
Official Warning — Use Is Not Recommended

jQuery’s API documentation strongly recommends against $.ajaxSetup(). Global defaults affect all Ajax traffic on the page — including code inside plugins that expect normal jQuery defaults. A plugin’s internal $.get() might suddenly POST to your base URL or inherit headers you never intended. We teach this API because legacy codebases still use it; for new code, set options explicitly per call or wrap $.ajax() in a small helper instead.

When you do encounter $.ajaxSetup() in the wild, understand that per-call options override setup defaults, that the method returns a merged PlainObject of ajaxSettings, and that global response handling belongs on $(document).on( "ajaxSuccess" ) — not in a success key inside setup. The examples below walk through official patterns adapted with JSONPlaceholder, plus a safer wrapper alternative for modern projects.

Understanding jQuery.ajaxSetup()

jQuery.ajaxSetup() does not send a network request. It mutates jQuery’s shared ajaxSettings defaults that every future Ajax helper merges into its per-request settings object. Call it once (or sparingly) at bootstrap — not inside click handlers. Options you set here apply page-wide until the next $.ajaxSetup() call replaces them entirely.

The same option keys documented for $.ajax() are valid — url, type / method, dataType, headers, global, cache, and more. After setup runs, a bare $.ajax({ data: { id: 1 } }) inherits whatever defaults you configured. Individual calls can still override any key by passing it explicitly in their own options object.

💡
Beginner Tip

Reach for explicit $.ajax({ ... }) options or a tiny $.apiGet() wrapper when you control all call sites. Reach for $.ajaxPrefilter() when you need per-request logic after defaults merge. Reserve $.ajaxSetup() for reading legacy code — not for new global configuration.

📝 Syntax

The official jQuery API accepts one signature:

1. Set defaults — jQuery.ajaxSetup( options )

jQuery
jQuery.ajaxSetup( options )

options is a PlainObject of key/value pairs — the same settings available to $.ajax(). All keys are optional.

2. Official demo — default url

jQuery
$.ajaxSetup({
  url: "ping.php"
});

// url not set here — uses ping.php from setup
$.ajax({
  data: { name: "Dan" }
});

3. Official demo — url, global: false, type: "POST"

jQuery
$.ajaxSetup({
  url: "/xmlhttp/",
  global: false,
  type: "POST"
});

// Sends POST to /xmlhttp/ with myData — no extra options needed
$.ajax({ data: myData });

Return value & merge behavior

  • $.ajaxSetup() returns a PlainObject — the merged ajaxSettings after your options are applied.
  • Each new $.ajaxSetup() call replaces previous global defaults — it does not deep-stack multiple setup calls.
  • Per-request options passed to $.ajax(), $.get(), $.post(), or .load() override matching setup keys for that call only.
  • Setup merge happens before $.ajaxPrefilter() handlers and before the per-request beforeSend callback.
  • Do not put success, error, or complete in setup — bind $(document).on( "ajaxSuccess" ), ajaxError, and ajaxComplete instead.

⚡ Quick Reference

GoalCode
Set global Ajax defaults$.ajaxSetup({ url: base, dataType: "json" })
Default base URL (official pattern)$.ajaxSetup({ url: "https://api.example.com/" })
Override on one call$.ajax({ url: "/other", dataType: "html" })
Disable global events site-wide$.ajaxSetup({ global: false })
Default POST method$.ajaxSetup({ type: "POST" })
Read merged settingsvar s = $.ajaxSetup({ cache: false });
Global response handler (correct)$(document).on("ajaxSuccess", fn)
Global response handler (avoid)$.ajaxSetup({ success: fn }) — affects all callers
Safer alternativeDefine $.apiGet(url, data) wrapper around $.ajax()

📋 ajaxSetup vs ajaxPrefilter vs explicit $.ajax() vs plugin wrapper

Four ways to share Ajax configuration — from global defaults (risky) to explicit, controlled call sites (preferred).

$.ajaxSetup()
global defaults

Merges static defaults into every future Ajax call — url, type, dataType, global:false; affects plugins; jQuery recommends against it

ajaxPrefilter
per-request hook

Runs after setup merge for each request — modify options dynamically, abort duplicates, inspect originalOptions; better for conditional logic

Explicit $.ajax()
per call

Pass full options on every call — verbose but safe, no hidden global state, plugins unaffected; best default for new code

Plugin wrapper
$.apiGet()

Small helper that calls $.ajax with your defaults — scoped to code you control, official jQuery-recommended pattern instead of ajaxSetup

Use $.ajaxSetup() only when maintaining legacy apps that already depend on it. Use $.ajaxPrefilter() for cross-cutting logic that must inspect each request. Use explicit $.ajax() or a wrapper function when you own all call sites — that keeps third-party plugins on jQuery’s normal defaults.

Examples Gallery

Five progressive examples from the official default-url pattern through dataType defaults, per-call overrides, the official global: false + POST combo, and a safer $.apiGet() wrapper that avoids global mutation. Each links to a Try-it lab where you can edit and run the code in the browser.

📚 Core Patterns

Official ajaxSetup patterns adapted with JSONPlaceholder — understand merge behavior before reaching for globals in production.

Example 1 — Official Default url Pattern — JSONPlaceholder Base

Adapted from jQuery’s docs: set a base URL once, then issue Ajax calls without repeating the full endpoint path.

jQuery
$.ajaxSetup({
  url: "https://jsonplaceholder.typicode.com/posts/"
});

$( "#load" ).on( "click", function() {
  // url not set here — setup supplies the base; we append the id
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    dataType: "json"
  }).done( function( post ) {
    $( "#result" ).text( "Loaded: " + post.title );
  } );
} );
Try It Yourself

How It Works

When the click handler passes an explicit url, that value wins over the setup default for this request. If you omit url entirely, jQuery uses the setup value. This mirrors the official ping.php example — callers only specify what differs from the default.

Example 2 — Default dataType: "json" for an API Module

Set JSON parsing as the default for a JSONPlaceholder API section so shorthand calls inherit it automatically.

jQuery
$.ajaxSetup({
  dataType: "json"
});

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

$( "#load-posts" ).on( "click", function() {
  $.get( "https://jsonplaceholder.typicode.com/posts" )
    .done( function( posts ) {
      $( "#count" ).text( posts.length + " posts" );
    } );
} );
Try It Yourself

How It Works

$.get() internally calls $.ajax(), so setup defaults apply to shorthands too. A global dataType default means every Ajax call expects JSON — including plugin requests that might need HTML or script. That global side effect is why jQuery warns against this API.

Example 3 — Per-Call url Override Still Works

Prove that explicit per-request options always beat setup defaults — one call stays on the API base, another hits a different endpoint.

jQuery
$.ajaxSetup({
  url: "https://jsonplaceholder.typicode.com/users/",
  dataType: "json"
});

$( "#same-base" ).on( "click", function() {
  // Uses setup url + appends id in the path via full url override pattern
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/users/1"
  }).done( function( user ) {
    $( "#log" ).text( "Default base: " + user.name );
  } );
} );

$( "#different-url" ).on( "click", function() {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    dataType: "json"
  }).done( function( post ) {
    $( "#log" ).text( "Override URL: " + post.title );
  } );
} );
Try It Yourself

How It Works

jQuery deep-merges the caller’s options object on top of setup defaults. Any key present in the per-call object replaces the setup value for that request. Unspecified keys still inherit from setup — so dataType: "json" applies to both buttons unless overridden.

📈 Official Defaults & Safer Alternatives

The documented global:false + POST pattern, and the wrapper jQuery recommends instead of global setup.

Example 4 — Official global: false + type: "POST" Defaults

Adapted from jQuery’s second official example: set url, disable global Ajax events, and default to POST — then send data with a minimal $.ajax() call.

jQuery
$.ajaxSetup({
  url: "https://jsonplaceholder.typicode.com/posts",
  global: false,
  type: "POST",
  dataType: "json"
});

$(document).on( "ajaxStart", function() {
  $( "#global-log" ).append( "ajaxStart fired\n" );
} );

$( "#send" ).on( "click", function() {
  var myData = { title: "Setup demo", body: "Posted via defaults", userId: 1 };

  $.ajax({ data: myData })
    .done( function( created ) {
      $( "#status" ).text( "Created post id: " + created.id );
    } );
} );
Try It Yourself

How It Works

The bare $.ajax({ data: myData }) inherits url, method, dataType, and global: false from setup. Global events like ajaxStart skip this request because global: false opts out. Remember: a global global: false default also silences global events for plugin Ajax you did not author.

Example 5 — Safer Alternative — $.apiGet() Helper Instead of ajaxSetup

jQuery’s recommended approach: a small wrapper that applies your defaults only to calls you control — no global mutation, no plugin surprises.

jQuery
var API_BASE = "https://jsonplaceholder.typicode.com";

function apiGet( path, data ) {
  return $.ajax({
    url: API_BASE + path,
    dataType: "json",
    data: data
  });
}

function apiPost( path, data ) {
  return $.ajax({
    url: API_BASE + path,
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify( data )
  });
}

$( "#fetch" ).on( "click", function() {
  apiGet( "/users/1" ).done( function( user ) {
    $( "#out" ).text( "Wrapper GET: " + user.email );
  } );
} );

$( "#create" ).on( "click", function() {
  apiPost( "/posts", { title: "Hi", body: "Safe defaults", userId: 1 } )
    .done( function( post ) {
      $( "#out" ).text( "Wrapper POST id: " + post.id );
    } );
} );
Try It Yourself

How It Works

The wrapper encapsulates base URL, dataType, and method without touching jQuery.ajaxSettings. You get DRY defaults scoped to your module. Pair with $.ajaxPrefilter() only when you need cross-cutting hooks — not $.ajaxSetup() for new projects.

🚀 Common Use Cases

  • Legacy base URL — old apps that call $.ajaxSetup({ url: "/api/" }) once at startup — understand before refactoring.
  • Default JSON dataType — API-heavy pages that assumed all responses are JSON — risky when plugins load HTML fragments.
  • Silent Ajax moduleglobal: false defaults to suppress ajaxStart / ajaxStop for background polling.
  • Default POST for forms — official pattern sets type: "POST" so bare $.ajax({ data }) sends POST bodies.
  • Reading merged settings — capture the PlainObject return value to inspect effective defaults after setup.
  • Maintaining plugin-heavy pages — audit whether existing $.ajaxSetup() breaks widget or analytics plugin traffic.
  • Migrating away from setup — replace globals with explicit options or apiGet() / apiPost() wrappers module by module.

🧠 ajaxSetup in the Ajax Pipeline

1

Caller invokes $.ajax()

Settings passed to $.ajax(), $.get(), $.post(), or .load() — the caller’s raw options.

$.ajax( settings )
2

$.ajaxSetup() merge

Global defaults from the last $.ajaxSetup() merge into caller settings — per-call keys override setup values.

ajaxSetup defaults
3

ajaxPrefilter handlers

Registered prefilters run on the merged object — dynamic logic, abort-on-retry, header injection after setup applied.

ajaxPrefilter
4

beforeSend

Per-request beforeSend runs — set headers on jqXHR or return false to cancel.

beforeSend
5

Transport sends

XHR sends bytes — global ajaxSend fires if global: true (the default unless setup changed it).

ajaxSend → network
6

Response callbacks & global events

Per-call .done() / .fail(), then bind global handlers with $(document).on( "ajaxSuccess" ) — not via ajaxSetup success key.

📝 Notes

  • Not recommended — jQuery’s official docs warn that $.ajaxSetup() can break plugins and other callers expecting default settings.
  • $.ajaxSetup() was added in jQuery 1.1; it returns a merged PlainObject of ajaxSettings.
  • Defaults apply to $.ajax(), $.get(), $.post(), and .load() until the next $.ajaxSetup() call.
  • Per-call options override setup defaults for that request — explicit url, type, or dataType on the call wins.
  • Do not put success, error, or complete in setup — use $(document).on( "ajaxSuccess" ), ajaxError, and ajaxComplete.
  • Each $.ajaxSetup() invocation replaces prior global defaults — it does not accumulate layered setups.
  • Setup merge runs before $.ajaxPrefilter() — prefilters see merged options including setup values.
  • For new code, prefer explicit per-call options or a small wrapper plugin over mutating shared ajaxSettings.

Browser Support

jQuery.ajaxSetup() is part of jQuery’s core Ajax module — not a native DOM API. It works wherever jQuery’s Ajax transport runs: all browsers supported by your jQuery version, including legacy IE with supported jQuery builds.

jQuery 1.1+

jQuery.ajaxSetup() method

Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. ajaxSetup arrived in jQuery 1.1 as a way to set default Ajax options. Despite long browser support, jQuery recommends avoiding global setup because of plugin compatibility risks.

100% With jQuery
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
$.ajaxSetup() Universal

Bottom line: Technically safe in any jQuery 1.1+ project, but architecturally risky on plugin-heavy pages. Prefer explicit $.ajax() options, wrapper helpers, or ajaxPrefilter for dynamic cross-cutting logic. Use global Ajax events on document for site-wide response handling.

Conclusion

jQuery.ajaxSetup() merges default Ajax options into every future request until the next setup call — handy in theory, dangerous in practice because plugins and third-party code share the same global defaults. Per-call options override setup, the method returns merged ajaxSettings, and global response handlers belong on $(document).on(), not inside setup.

For new projects, skip global setup and use explicit options or a wrapper like apiGet(). Continue with the ajaxTransport() tutorial to learn custom send/abort transports for advanced dataTypes, then explore ajaxStart for page-wide loading indicators.

💡 Best Practices

✅ Do

  • Set Ajax options explicitly on each $.ajax() call you control
  • Wrap repeated defaults in a small apiGet() / apiPost() helper
  • Bind global response handlers with $(document).on( "ajaxSuccess" )
  • Override setup per call when maintaining legacy code that uses ajaxSetup
  • Use $.ajaxPrefilter() for dynamic cross-cutting logic instead of static globals

❌ Don’t

  • Call $.ajaxSetup() on plugin-heavy pages without auditing side effects
  • Put success, error, or complete callbacks inside ajaxSetup
  • Assume setup stacks — each call replaces previous global defaults entirely
  • Set global: false globally unless every caller should opt out of Ajax events
  • Use ajaxSetup in new code when a wrapper or explicit options achieve the same goal

Key Takeaways

Knowledge Unlocked

Six things to remember about $.ajaxSetup()

Global defaults, local overrides, avoid in new code.

6
Core concepts
win 02

Override wins

Per-call options

Caller
warn 03

Not recommended

Plugin risk

Avoid
obj 04

PlainObject

ajaxSettings

Return
evt 05

Global events

on document

ajaxSuccess
wrap 06

Wrapper safer

apiGet helper

Best

❓ Frequently Asked Questions

jQuery.ajaxSetup() sets default option values that jQuery merges into every future Ajax request — including $.ajax(), $.get(), $.post(), and .load() — until the next call to $.ajaxSetup(). It returns a PlainObject containing the merged ajaxSettings. Per-call options passed to an individual request override these defaults.
Global defaults affect every Ajax caller on the page, including third-party plugins that expect jQuery's normal defaults. A plugin's internal $.get() might suddenly hit your base URL, send POST instead of GET, or inherit headers you never intended. jQuery's official docs say to set options explicitly per call or wrap $.ajax() in a small plugin instead of mutating shared defaults.
Yes. Any option you pass to $.ajax(), $.get(), $.post(), or .load() overrides the matching key from $.ajaxSetup() for that call only. For example, if ajaxSetup sets url to a base path, one $.ajax({ url: "https://other.example.com/data" }) still uses the full override URL.
$.ajaxSetup() sets static default values merged into each request's settings object — url prefix, dataType, global:false, type. $.ajaxPrefilter() registers a handler that runs per request with access to merged options and originalOptions, letting you apply conditional logic, abort duplicates, or return a dataType string. Prefilters run after ajaxSetup merge; use prefilters for dynamic behavior, not ajaxSetup.
Putting success, error, or complete in $.ajaxSetup() attaches those handlers to every Ajax call site-wide — including plugin traffic you cannot see. jQuery recommends binding global response handlers with $(document).on("ajaxSuccess"), $(document).on("ajaxError"), and $(document).on("ajaxComplete") instead, so you opt into event-driven global behavior without hijacking individual request callbacks.
Call $.ajaxSetup() again with a fresh options object — each invocation replaces the previous global defaults entirely (merged into jQuery.ajaxSettings), not layered on top. To restore jQuery's built-in defaults, pass an empty object {} or only the keys you want to change back. For app code, prefer avoiding global setup altogether and resetting is rarely needed if you use explicit per-call options or a wrapper function.
Did you know?

jQuery added $.ajaxSetup() in version 1.1 — years before $.ajaxPrefilter() arrived in 1.5. The official documentation has carried the “use is not recommended” warning because a single setup call changes defaults for every Ajax derivative on the page, including code inside jQuery UI, validation plugins, and analytics snippets. The docs explicitly suggest defining a simple plugin wrapper instead — the same pattern as our apiGet() example — so your defaults stay scoped to code you own.

Next: ajaxTransport() Method

Learn custom Ajax transports with send() and abort() — the lowest-level extension point when prefilters are not enough.

ajaxTransport() 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.

6 people found this page helpful