How to Set Global AJAX Defaults with jQuery $.ajaxSetup()
This article explains how to configure global AJAX defaults in jQuery
using the $.ajaxSetup() method. You will learn the syntax,
explore practical code examples for common configurations such as
authentication headers, timeouts, and error handling, and discover best
practices for managing global settings without unintended side effects
across your application.
What is $.ajaxSetup()?
The $.ajaxSetup() method allows you to define default
configuration options for all future jQuery AJAX requests on a page,
including $.ajax(), $.get(),
$.post(), and $.getJSON(). Any options passed
to $.ajaxSetup() serve as the fallback configuration unless
explicitly overridden in an individual request.
Syntax
$.ajaxSetup(options);options: An object containing key-value pairs representing the default settings to apply to subsequent AJAX calls.
Common Use Cases and Examples
1. Setting Common Headers (e.g., CSRF and Authorization)
One of the most frequent uses of $.ajaxSetup() is
attaching security tokens or authentication headers to every request
automatically.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
}
});
// Subsequent requests automatically include these headers
$.post('/api/profile/update', { name: 'Jane Doe' });2. Configuring Global Timeouts and Cache Control
You can enforce a universal timeout and disable caching for
GET requests globally.
$.ajaxSetup({
timeout: 5000, // Abort requests that take longer than 5 seconds
cache: false // Append a timestamp to GET URLs to bypass browser cache
});3. Defining Global Callbacks and Error Handling
You can define hooks like beforeSend,
complete, or error to run during the lifecycle
of every request.
$.ajaxSetup({
beforeSend: function(xhr, settings) {
// Show a global loading spinner
$('#loading-spinner').show();
},
complete: function(xhr, status) {
// Hide the global loading spinner
$('#loading-spinner').hide();
},
error: function(xhr, status, error) {
if (xhr.status === 401) {
// Redirect to login if unauthorized
window.location.href = '/login';
} else {
console.error('AJAX Error:', error);
}
}
});Overriding Global Defaults
Global settings do not lock you into fixed parameters. Any option set
in $.ajaxSetup() can be overridden by passing a different
value directly into an individual AJAX call.
// This request will wait up to 15 seconds instead of the global 5-second default
$.ajax({
url: '/api/generate-report',
method: 'POST',
timeout: 15000
});Important Considerations
- Global Scope:
$.ajaxSetup()alters settings globally. If third-party plugins or scripts on your page rely on jQuery's default AJAX behavior, modified global defaults may cause unexpected behavior in those components. - Alternative for Global Events: For tracking global
application state (such as showing/hiding spinners or centralizing error
notifications), jQuery provides global event handlers such as
$(document).ajaxStart(),$(document).ajaxStop(), and$(document).ajaxError(). These handlers are often safer alternatives for UI-related tasks than modifying$.ajaxSetup().