Full-featured AJAX solution with promises, request/response preprocessing, and multiple data formats. jQuery's AJAX implementation provides a consistent, powerful interface for all HTTP communications.
The fundamental AJAX method providing complete control over HTTP requests.
/**
* Perform asynchronous HTTP request with full configuration options
* @param url - Request URL
* @param settings - Configuration options
* @returns jqXHR object (enhanced Promise)
*/
$.ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR;
$.ajax(settings: JQueryAjaxSettings): JQueryXHR;
interface JQueryAjaxSettings {
// Request configuration
url?: string;
type?: string; // HTTP method (GET, POST, PUT, DELETE, etc.)
method?: string; // Alias for type
data?: any; // Data to send
dataType?: string; // Expected response type
contentType?: string; // Request content type
// Request headers and authentication
headers?: object; // Additional headers
username?: string; // Basic auth username
password?: string; // Basic auth password
// Request behavior
async?: boolean; // Asynchronous request (default true)
cache?: boolean; // Cache requests (default true except for dataType 'script' and 'jsonp')
timeout?: number; // Request timeout in milliseconds
traditional?: boolean; // Use traditional parameter serialization
// Data processing
processData?: boolean; // Process data before sending (default true)
global?: boolean; // Trigger global AJAX events (default true)
ifModified?: boolean; // Only succeed if response has changed
// Callbacks
beforeSend?: function; // Pre-request callback
success?: function; // Success callback
error?: function; // Error callback
complete?: function; // Completion callback (success or error)
// Advanced options
context?: any; // Context for callbacks
xhr?: function; // Custom XMLHttpRequest factory
xhrFields?: object; // Properties to set on native XHR object
statusCode?: object; // Status code specific callbacks
// Cross-domain
crossDomain?: boolean; // Force cross-domain request
jsonp?: string; // JSONP callback parameter name
jsonpCallback?: string; // JSONP callback function name
}
interface JQueryXHR extends Promise<any> {
// XMLHttpRequest properties
readyState: number;
status: number;
statusText: string;
responseText: string;
responseXML?: Document;
responseJSON?: any;
// Additional methods
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
overrideMimeType(type: string): void;
setRequestHeader(name: string, value: string): void;
// Promise methods (inherited)
done(doneCallback: function): JQueryXHR;
fail(failCallback: function): JQueryXHR;
always(alwaysCallback: function): JQueryXHR;
then(doneCallback?: function, failCallback?: function, progressCallback?: function): JQueryXHR;
catch(failCallback: function): JQueryXHR;
pipe(doneFilter?: function, failFilter?: function, progressFilter?: function): JQueryXHR;
progress(progressCallback: function): JQueryXHR;
state(): string;
}Usage Examples:
// Basic AJAX request
$.ajax({
url: '/api/users',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log('Users:', data);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
// POST with data
$.ajax({
url: '/api/users',
type: 'POST',
data: {
name: 'John Doe',
email: 'john@example.com'
},
dataType: 'json'
}).done(function(response) {
console.log('User created:', response);
}).fail(function(xhr) {
console.error('Failed to create user:', xhr.responseText);
});
// Advanced configuration
$.ajax({
url: '/api/data',
type: 'POST',
data: JSON.stringify({ key: 'value' }),
contentType: 'application/json',
dataType: 'json',
timeout: 5000,
headers: {
'Authorization': 'Bearer ' + token,
'X-Custom-Header': 'value'
},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(data, textStatus, xhr) {
console.log('Success:', data);
},
error: function(xhr, textStatus, errorThrown) {
console.error('Error:', textStatus, errorThrown);
},
complete: function(xhr, textStatus) {
console.log('Request completed:', textStatus);
}
});Simplified methods for common AJAX patterns.
/**
* Perform HTTP GET request
* @param url - Request URL
* @param data - Optional data to send as query parameters
* @param success - Success callback
* @param dataType - Expected response data type
* @returns jqXHR object
*/
$.get(url: string): JQueryXHR;
$.get(url: string, data: any): JQueryXHR;
$.get(url: string, success: function): JQueryXHR;
$.get(url: string, data: any, success: function): JQueryXHR;
$.get(url: string, data: any, success: function, dataType: string): JQueryXHR;
/**
* Perform HTTP POST request
*/
$.post(url: string): JQueryXHR;
$.post(url: string, data: any): JQueryXHR;
$.post(url: string, success: function): JQueryXHR;
$.post(url: string, data: any, success: function): JQueryXHR;
$.post(url: string, data: any, success: function, dataType: string): JQueryXHR;
/**
* Load JSON data via HTTP GET
* @param url - Request URL
* @param data - Optional data to send as query parameters
* @param success - Success callback receiving JSON data
* @returns jqXHR object
*/
$.getJSON(url: string): JQueryXHR;
$.getJSON(url: string, data: any): JQueryXHR;
$.getJSON(url: string, success: function): JQueryXHR;
$.getJSON(url: string, data: any, success: function): JQueryXHR;
/**
* Load and execute JavaScript file
* @param url - Script URL
* @param success - Optional success callback
* @returns jqXHR object
*/
$.getScript(url: string): JQueryXHR;
$.getScript(url: string, success: function): JQueryXHR;Usage Examples:
// Simple GET request
$.get('/api/users', function(data) {
console.log('Users:', data);
});
// GET with query parameters
$.get('/api/search', { q: 'jquery', limit: 10 }, function(results) {
displayResults(results);
});
// POST form data
$.post('/api/login', {
username: 'user',
password: 'pass'
}, function(response) {
if (response.success) {
window.location.href = '/dashboard';
}
}, 'json');
// Load JSON data
$.getJSON('/api/config.json', function(config) {
initializeApp(config);
});
// Load external script
$.getScript('https://cdn.example.com/plugin.js', function() {
// Plugin is now loaded and available
initializePlugin();
});
// Chaining with promises
$.get('/api/user/123')
.done(function(user) {
return $.get('/api/user/' + user.id + '/posts');
})
.done(function(posts) {
displayPosts(posts);
})
.fail(function() {
showError('Failed to load user data');
});Load remote content directly into DOM elements.
/**
* Load HTML content from server into elements
* @param url - URL to load content from
* @param data - Optional data to send with request
* @param complete - Optional callback when loading completes
* @returns jQuery object for chaining
*/
load(url: string): jQuery;
load(url: string, data: any): jQuery;
load(url: string, complete: function): jQuery;
load(url: string, data: any, complete: function): jQuery;Usage Examples:
// Load content into element
$('#content').load('/api/content.html');
// Load with data
$('#results').load('/search', { q: 'jquery' });
// Load with callback
$('#sidebar').load('/sidebar.html', function(response, status, xhr) {
if (status === 'error') {
$(this).html('Error loading sidebar');
}
});
// Load fragment of remote page
$('#quotes').load('/page.html #quote-of-day');
// Load with form data
$('#content').load('/submit', $('#myForm').serialize());Configure default settings for all AJAX requests.
/**
* Set default settings for AJAX requests
* @param options - Default settings to apply to all AJAX requests
*/
$.ajaxSetup(options: JQueryAjaxSettings): void;
// Global AJAX settings object
$.ajaxSettings: JQueryAjaxSettings;
// Active request counter
$.active: number;Usage Examples:
// Set global defaults
$.ajaxSetup({
timeout: 10000,
headers: {
'X-API-Key': 'your-api-key'
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error);
}
});
// Now all AJAX requests use these defaults
$.get('/api/data'); // Will have 10 second timeout and API key header
// Override defaults for specific request
$.ajax({
url: '/api/special',
timeout: 30000 // Overrides global timeout
});
// Monitor active requests
function checkActivity() {
if ($.active > 0) {
$('#loading').show();
} else {
$('#loading').hide();
}
}
$(document).ajaxStart(checkActivity);
$(document).ajaxComplete(checkActivity);Global events triggered during AJAX lifecycle for application-wide handling.
// Global AJAX events (can be bound to any element, typically document)
'ajaxStart' // First AJAX request starts
'ajaxStop' // All AJAX requests complete
'ajaxSend' // Before each request is sent
'ajaxSuccess' // Each successful request
'ajaxError' // Each failed request
'ajaxComplete' // Each request completes (success or error)Usage Examples:
// Global loading indicator
$(document).ajaxStart(function() {
$('#loading-indicator').show();
}).ajaxStop(function() {
$('#loading-indicator').hide();
});
// Log all AJAX activity
$(document).ajaxSend(function(event, xhr, settings) {
console.log('AJAX request sent:', settings.url);
});
$(document).ajaxSuccess(function(event, xhr, settings) {
console.log('AJAX request succeeded:', settings.url);
});
$(document).ajaxError(function(event, xhr, settings, thrownError) {
console.error('AJAX request failed:', settings.url, thrownError);
});
// Specific element events
$('#api-section').ajaxComplete(function(event, xhr, settings) {
// Handle completion of AJAX requests related to this section
});Convert form data and objects to URL-encoded strings.
/**
* Serialize object or array to URL-encoded string
* @param obj - Object or array to serialize
* @param traditional - Use traditional parameter serialization
* @returns URL-encoded string
*/
$.param(obj: any, traditional?: boolean): string;Usage Examples:
// Serialize object
const data = { name: 'John', age: 30, city: 'Boston' };
const serialized = $.param(data);
// Result: "name=John&age=30&city=Boston"
// Serialize array
const array = [
{ name: 'name', value: 'John' },
{ name: 'age', value: 30 }
];
const serializedArray = $.param(array);
// Result: "name=John&age=30"
// Traditional serialization for arrays
const complexData = {
users: ['John', 'Jane'],
active: true
};
const modern = $.param(complexData);
// Result: "users%5B%5D=John&users%5B%5D=Jane&active=true"
const traditional = $.param(complexData, true);
// Result: "users=John&users=Jane&active=true"
// Use with AJAX
$.post('/api/submit', $.param(formData), function(response) {
console.log('Submitted successfully');
});Modify requests before they are sent using prefilters.
/**
* Register prefilter to modify AJAX requests before sending
* @param dataTypes - Data types to apply prefilter to
* @param handler - Prefilter function
*/
$.ajaxPrefilter(dataTypes: string, handler: function): void;
$.ajaxPrefilter(handler: function): void;Usage Examples:
// Add authentication to all JSON requests
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (!options.headers) {
options.headers = {};
}
options.headers.Authorization = 'Bearer ' + getAuthToken();
});
// Convert all POST requests to PUT for specific URLs
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type === 'POST' && options.url.indexOf('/api/update/') === 0) {
options.type = 'PUT';
}
});
// Add CSRF tokens
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.type !== 'GET') {
if (!options.data) {
options.data = {};
}
if (typeof options.data === 'string') {
options.data += '&_token=' + getCsrfToken();
} else {
options.data._token = getCsrfToken();
}
}
});Implement custom communication protocols.
/**
* Register custom transport for handling specific data types
* @param dataType - Data type to handle
* @param handler - Transport factory function
*/
$.ajaxTransport(dataType: string, handler: function): void;Usage Examples:
// Custom WebSocket transport
$.ajaxTransport('websocket', function(options, originalOptions, jqXHR) {
if (options.url.indexOf('ws://') === 0) {
return {
send: function(headers, completeCallback) {
const ws = new WebSocket(options.url);
ws.onmessage = function(event) {
completeCallback(200, 'OK', { text: event.data });
};
ws.onerror = function() {
completeCallback(500, 'Error');
};
if (options.data) {
ws.onopen = function() {
ws.send(options.data);
};
}
},
abort: function() {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.close();
}
}
};
}
});
// Use custom transport
$.ajax({
url: 'ws://example.com/socket',
dataType: 'websocket',
data: 'Hello WebSocket!'
});Implement custom caching strategies for AJAX responses.
// Cache management using $.ajaxSetup and custom logic
$.lastModified: object; // Last-Modified header cache
$.etag: object; // ETag header cacheUsage Examples:
// Simple response caching
const responseCache = {};
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (options.cache !== false && responseCache[options.url]) {
const cached = responseCache[options.url];
setTimeout(function() {
jqXHR.resolve(cached.data, 'success', jqXHR);
}, 0);
return false; // Prevent actual request
}
});
$(document).ajaxSuccess(function(event, xhr, settings) {
if (settings.cache !== false) {
responseCache[settings.url] = {
data: xhr.responseJSON || xhr.responseText,
timestamp: Date.now()
};
}
});
// Cache with expiration
function getCachedResponse(url, maxAge = 300000) { // 5 minutes default
const cached = responseCache[url];
if (cached && (Date.now() - cached.timestamp) < maxAge) {
return cached.data;
}
return null;
}// Comprehensive error handling
$.ajax({
url: '/api/data',
type: 'GET',
timeout: 5000,
retries: 3,
retryInterval: 1000
}).done(function(data) {
processData(data);
}).fail(function(xhr, textStatus, errorThrown) {
handleAjaxError(xhr, textStatus, errorThrown);
}).always(function() {
hideLoadingSpinner();
});
function handleAjaxError(xhr, textStatus, errorThrown) {
let message = 'An error occurred';
if (textStatus === 'timeout') {
message = 'Request timed out. Please try again.';
} else if (textStatus === 'abort') {
message = 'Request was cancelled.';
} else if (xhr.status === 404) {
message = 'Requested resource not found.';
} else if (xhr.status === 500) {
message = 'Server error. Please try again later.';
} else if (xhr.responseJSON && xhr.responseJSON.message) {
message = xhr.responseJSON.message;
}
showErrorMessage(message);
}
// Retry logic
function ajaxWithRetry(options, maxRetries = 3) {
return $.ajax(options).fail(function(xhr, textStatus) {
if (maxRetries > 0 && textStatus !== 'abort') {
setTimeout(function() {
ajaxWithRetry(options, maxRetries - 1);
}, 1000);
}
});
}