Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API
Full-featured Ajax implementation with XMLHttpRequest, JSONP support, and form handling capabilities. Provides jQuery-compatible API with modern browser optimizations.
The main Ajax method providing complete control over HTTP requests.
/**
* Perform asynchronous HTTP request
* @param options - Configuration object for the request
* @returns XMLHttpRequest object (jqXHR-like)
*/
$.ajax(options);Ajax Options:
interface AjaxOptions {
/** Request URL */
url?: string;
/** HTTP method (GET, POST, PUT, DELETE, etc.) */
type?: string;
/** Request data (string, object, or FormData) */
data?: any;
/** Content-Type header for request */
contentType?: string;
/** Expected response data type (json, xml, html, text, script, jsonp) */
dataType?: string;
/** Request timeout in milliseconds */
timeout?: number;
/** Success callback */
success?: (data: any, status: string, xhr: XMLHttpRequest) => void;
/** Error callback */
error?: (xhr: XMLHttpRequest, errorType: string, error?: Error) => void;
/** Complete callback (always called) */
complete?: (xhr: XMLHttpRequest, status: string) => void;
/** Before send callback */
beforeSend?: (xhr: XMLHttpRequest, settings: AjaxOptions) => boolean | void;
/** Custom headers object */
headers?: {[key: string]: string};
/** Whether to process data (default: true) */
processData?: boolean;
/** Whether to set cache headers (default: true) */
cache?: boolean;
/** Cross-domain request settings */
crossDomain?: boolean;
/** Username for authentication */
username?: string;
/** Password for authentication */
password?: string;
/** XHR fields to set */
xhrFields?: {[key: string]: any};
}Usage Examples:
// Basic GET request
$.ajax({
url: '/api/users',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log('Users:', data);
},
error: function(xhr, errorType, error) {
console.log('Request failed:', errorType);
}
});
// POST with data
$.ajax({
url: '/api/users',
type: 'POST',
data: {name: 'John', email: 'john@example.com'},
dataType: 'json',
success: function(data) {
console.log('User created:', data);
}
});
// Custom headers and options
$.ajax({
url: '/api/data',
type: 'GET',
headers: {
'Authorization': 'Bearer token123',
'X-Custom-Header': 'value'
},
timeout: 5000,
beforeSend: function(xhr, settings) {
console.log('Sending request to:', settings.url);
}
});Shorthand methods for common HTTP operations.
/**
* Perform GET request
* @param url - Request URL
* @param data - Optional query parameters
* @param success - Success callback
* @param dataType - Expected response type
* @returns XMLHttpRequest object
*/
$.get(url, data, success, dataType);
/**
* Perform POST request
* @param url - Request URL
* @param data - Request data
* @param success - Success callback
* @param dataType - Expected response type
* @returns XMLHttpRequest object
*/
$.post(url, data, success, dataType);
/**
* Perform GET request expecting JSON response
* @param url - Request URL
* @param data - Optional query parameters
* @param success - Success callback
* @returns XMLHttpRequest object
*/
$.getJSON(url, data, success);
/**
* Load HTML content into elements
* @param url - URL to load content from
* @param data - Optional data to send with request
* @param success - Optional callback after loading
* @returns Original collection
*/
$.fn.load(url, data, success);Usage Examples:
// Simple GET request
$.get('/api/data', function(data) {
console.log('Data received:', data);
});
// GET with parameters
$.get('/api/search', {q: 'zepto', limit: 10}, function(results) {
console.log('Search results:', results);
}, 'json');
// POST request
$.post('/api/save', {name: 'value'}, function(response) {
console.log('Saved:', response);
});
// JSON GET request
$.getJSON('/api/config', function(config) {
console.log('Config loaded:', config);
});
// Load HTML into element
$('#content').load('/fragments/sidebar.html', function() {
console.log('Sidebar loaded');
});
// Load with data and callback
$('#results').load('/search', {query: 'test'}, function(response, status) {
if (status === 'success') {
console.log('Search results loaded');
}
});Cross-domain requests using JSONP (JSON with Padding).
/**
* Perform JSONP request
* @param options - JSONP request options
* @param deferred - Optional deferred object
* @returns XMLHttpRequest-like object
*/
$.ajaxJSONP(options, deferred);Usage Examples:
// JSONP request
$.ajax({
url: 'https://api.external.com/data',
dataType: 'jsonp',
success: function(data) {
console.log('JSONP data:', data);
}
});
// JSONP with custom callback parameter
$.ajax({
url: 'https://api.example.com/search',
dataType: 'jsonp',
jsonp: 'callback', // Custom callback parameter name
data: {q: 'search term'},
success: function(data) {
console.log('Search results:', data);
}
});Utilities for converting data to URL-encoded format.
/**
* Serialize object to URL-encoded string
* @param obj - Object to serialize
* @param traditional - Use traditional array serialization
* @returns URL-encoded string
*/
$.param(obj, traditional);Usage Examples:
// Basic serialization
const params = $.param({name: 'John', age: 30});
// Result: "name=John&age=30"
// Array serialization
const data = {
users: ['john', 'jane'],
active: true
};
const modern = $.param(data);
// Result: "users[]=john&users[]=jane&active=true"
const traditional = $.param(data, true);
// Result: "users=john&users=jane&active=true"
// Complex objects
const complex = {
user: {name: 'John', details: {age: 30}},
tags: ['admin', 'user']
};
const serialized = $.param(complex);Default settings and activity tracking.
/**
* Default Ajax settings object
*/
$.ajaxSettings;
/**
* Number of active Ajax requests
*/
$.active;Ajax Settings Properties:
interface AjaxSettings {
/** Default request type */
type: string; // 'GET'
/** Default timeout */
timeout: number; // 0 (no timeout)
/** Default data type */
dataType: string; // undefined
/** Default content type */
contentType: string; // 'application/x-www-form-urlencoded; charset=UTF-8'
/** Process data by default */
processData: boolean; // true
/** Enable caching by default */
cache: boolean; // true
/** Default headers */
headers: {[key: string]: string};
/** Cross-domain detection */
crossDomain: boolean; // false
/** JSONP callback parameter name */
jsonp: string; // 'callback'
/** Accept headers for different data types */
accepts: {[key: string]: string};
}Usage Examples:
// Modify global settings
$.ajaxSettings.timeout = 10000; // 10 second default timeout
$.ajaxSettings.headers['X-Requested-With'] = 'XMLHttpRequest';
// Check active requests
console.log('Active requests:', $.active);
// Global error handling
$(document).ajaxError(function(event, xhr, settings, error) {
console.log('Ajax error:', error);
});
// Global success handling
$(document).ajaxSuccess(function(event, xhr, settings) {
console.log('Ajax success:', settings.url);
});Methods specifically designed for form handling.
/**
* Serialize form data to URL-encoded string
* @returns Serialized form data
*/
$.fn.serialize();
/**
* Serialize form data to array of name/value objects
* @returns Array of {name, value} objects
*/
$.fn.serializeArray();Usage Examples:
// Serialize form for submission
$('#myForm').serialize();
// Result: "name=John&email=john%40example.com&age=30"
// Get form data as array
const formData = $('#myForm').serializeArray();
// Result: [
// {name: 'name', value: 'John'},
// {name: 'email', value: 'john@example.com'},
// {name: 'age', value: '30'}
// ]
// Submit form via Ajax
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('/api/submit', $(this).serialize(), function(response) {
console.log('Form submitted:', response);
});
});Comprehensive error handling and status codes.
// Error types passed to error callbacks:
// - 'timeout': Request timed out
// - 'error': General error
// - 'abort': Request aborted
// - 'parsererror': JSON/XML parsing failed
// HTTP status handling
$.ajax({
url: '/api/data',
statusCode: {
404: function() {
console.log('Page not found');
},
500: function() {
console.log('Server error');
}
}
});Working with HTTP headers.
// Set request headers
$.ajax({
url: '/api/data',
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
}
});
// Access response headers in success callback
$.ajax({
url: '/api/data',
success: function(data, status, xhr) {
const contentType = xhr.getResponseHeader('Content-Type');
const lastModified = xhr.getResponseHeader('Last-Modified');
console.log('Response headers:', contentType, lastModified);
}
});Optimizations and recommendations for Ajax usage:
// Cache GET requests
$.ajaxSettings.cache = true;
// Use appropriate data types
$.getJSON('/api/data'); // Better than $.get with manual parsing
// Handle errors gracefully
$.ajax({
url: '/api/data',
timeout: 5000,
error: function(xhr, errorType) {
if (errorType === 'timeout') {
// Handle timeout specifically
}
}
});
// Abort requests when needed
const xhr = $.get('/long-request');
// Later...
xhr.abort();
// Use FormData for file uploads
const formData = new FormData($('#fileForm')[0]);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false
});