0
# Ajax and HTTP
1
2
Full-featured Ajax implementation with XMLHttpRequest, JSONP support, and form handling capabilities. Provides jQuery-compatible API with modern browser optimizations.
3
4
## Capabilities
5
6
### Core Ajax Method
7
8
The main Ajax method providing complete control over HTTP requests.
9
10
```javascript { .api }
11
/**
12
* Perform asynchronous HTTP request
13
* @param options - Configuration object for the request
14
* @returns XMLHttpRequest object (jqXHR-like)
15
*/
16
$.ajax(options);
17
```
18
19
**Ajax Options:**
20
21
```javascript { .api }
22
interface AjaxOptions {
23
/** Request URL */
24
url?: string;
25
/** HTTP method (GET, POST, PUT, DELETE, etc.) */
26
type?: string;
27
/** Request data (string, object, or FormData) */
28
data?: any;
29
/** Content-Type header for request */
30
contentType?: string;
31
/** Expected response data type (json, xml, html, text, script, jsonp) */
32
dataType?: string;
33
/** Request timeout in milliseconds */
34
timeout?: number;
35
/** Success callback */
36
success?: (data: any, status: string, xhr: XMLHttpRequest) => void;
37
/** Error callback */
38
error?: (xhr: XMLHttpRequest, errorType: string, error?: Error) => void;
39
/** Complete callback (always called) */
40
complete?: (xhr: XMLHttpRequest, status: string) => void;
41
/** Before send callback */
42
beforeSend?: (xhr: XMLHttpRequest, settings: AjaxOptions) => boolean | void;
43
/** Custom headers object */
44
headers?: {[key: string]: string};
45
/** Whether to process data (default: true) */
46
processData?: boolean;
47
/** Whether to set cache headers (default: true) */
48
cache?: boolean;
49
/** Cross-domain request settings */
50
crossDomain?: boolean;
51
/** Username for authentication */
52
username?: string;
53
/** Password for authentication */
54
password?: string;
55
/** XHR fields to set */
56
xhrFields?: {[key: string]: any};
57
}
58
```
59
60
**Usage Examples:**
61
62
```javascript
63
// Basic GET request
64
$.ajax({
65
url: '/api/users',
66
type: 'GET',
67
dataType: 'json',
68
success: function(data) {
69
console.log('Users:', data);
70
},
71
error: function(xhr, errorType, error) {
72
console.log('Request failed:', errorType);
73
}
74
});
75
76
// POST with data
77
$.ajax({
78
url: '/api/users',
79
type: 'POST',
80
data: {name: 'John', email: 'john@example.com'},
81
dataType: 'json',
82
success: function(data) {
83
console.log('User created:', data);
84
}
85
});
86
87
// Custom headers and options
88
$.ajax({
89
url: '/api/data',
90
type: 'GET',
91
headers: {
92
'Authorization': 'Bearer token123',
93
'X-Custom-Header': 'value'
94
},
95
timeout: 5000,
96
beforeSend: function(xhr, settings) {
97
console.log('Sending request to:', settings.url);
98
}
99
});
100
```
101
102
### Convenience Methods
103
104
Shorthand methods for common HTTP operations.
105
106
```javascript { .api }
107
/**
108
* Perform GET request
109
* @param url - Request URL
110
* @param data - Optional query parameters
111
* @param success - Success callback
112
* @param dataType - Expected response type
113
* @returns XMLHttpRequest object
114
*/
115
$.get(url, data, success, dataType);
116
117
/**
118
* Perform POST request
119
* @param url - Request URL
120
* @param data - Request data
121
* @param success - Success callback
122
* @param dataType - Expected response type
123
* @returns XMLHttpRequest object
124
*/
125
$.post(url, data, success, dataType);
126
127
/**
128
* Perform GET request expecting JSON response
129
* @param url - Request URL
130
* @param data - Optional query parameters
131
* @param success - Success callback
132
* @returns XMLHttpRequest object
133
*/
134
$.getJSON(url, data, success);
135
136
/**
137
* Load HTML content into elements
138
* @param url - URL to load content from
139
* @param data - Optional data to send with request
140
* @param success - Optional callback after loading
141
* @returns Original collection
142
*/
143
$.fn.load(url, data, success);
144
```
145
146
**Usage Examples:**
147
148
```javascript
149
// Simple GET request
150
$.get('/api/data', function(data) {
151
console.log('Data received:', data);
152
});
153
154
// GET with parameters
155
$.get('/api/search', {q: 'zepto', limit: 10}, function(results) {
156
console.log('Search results:', results);
157
}, 'json');
158
159
// POST request
160
$.post('/api/save', {name: 'value'}, function(response) {
161
console.log('Saved:', response);
162
});
163
164
// JSON GET request
165
$.getJSON('/api/config', function(config) {
166
console.log('Config loaded:', config);
167
});
168
169
// Load HTML into element
170
$('#content').load('/fragments/sidebar.html', function() {
171
console.log('Sidebar loaded');
172
});
173
174
// Load with data and callback
175
$('#results').load('/search', {query: 'test'}, function(response, status) {
176
if (status === 'success') {
177
console.log('Search results loaded');
178
}
179
});
180
```
181
182
### JSONP Support
183
184
Cross-domain requests using JSONP (JSON with Padding).
185
186
```javascript { .api }
187
/**
188
* Perform JSONP request
189
* @param options - JSONP request options
190
* @param deferred - Optional deferred object
191
* @returns XMLHttpRequest-like object
192
*/
193
$.ajaxJSONP(options, deferred);
194
```
195
196
**Usage Examples:**
197
198
```javascript
199
// JSONP request
200
$.ajax({
201
url: 'https://api.external.com/data',
202
dataType: 'jsonp',
203
success: function(data) {
204
console.log('JSONP data:', data);
205
}
206
});
207
208
// JSONP with custom callback parameter
209
$.ajax({
210
url: 'https://api.example.com/search',
211
dataType: 'jsonp',
212
jsonp: 'callback', // Custom callback parameter name
213
data: {q: 'search term'},
214
success: function(data) {
215
console.log('Search results:', data);
216
}
217
});
218
```
219
220
### Data Serialization
221
222
Utilities for converting data to URL-encoded format.
223
224
```javascript { .api }
225
/**
226
* Serialize object to URL-encoded string
227
* @param obj - Object to serialize
228
* @param traditional - Use traditional array serialization
229
* @returns URL-encoded string
230
*/
231
$.param(obj, traditional);
232
```
233
234
**Usage Examples:**
235
236
```javascript
237
// Basic serialization
238
const params = $.param({name: 'John', age: 30});
239
// Result: "name=John&age=30"
240
241
// Array serialization
242
const data = {
243
users: ['john', 'jane'],
244
active: true
245
};
246
const modern = $.param(data);
247
// Result: "users[]=john&users[]=jane&active=true"
248
249
const traditional = $.param(data, true);
250
// Result: "users=john&users=jane&active=true"
251
252
// Complex objects
253
const complex = {
254
user: {name: 'John', details: {age: 30}},
255
tags: ['admin', 'user']
256
};
257
const serialized = $.param(complex);
258
```
259
260
### Global Ajax Settings
261
262
Default settings and activity tracking.
263
264
```javascript { .api }
265
/**
266
* Default Ajax settings object
267
*/
268
$.ajaxSettings;
269
270
/**
271
* Number of active Ajax requests
272
*/
273
$.active;
274
```
275
276
**Ajax Settings Properties:**
277
278
```javascript { .api }
279
interface AjaxSettings {
280
/** Default request type */
281
type: string; // 'GET'
282
/** Default timeout */
283
timeout: number; // 0 (no timeout)
284
/** Default data type */
285
dataType: string; // undefined
286
/** Default content type */
287
contentType: string; // 'application/x-www-form-urlencoded; charset=UTF-8'
288
/** Process data by default */
289
processData: boolean; // true
290
/** Enable caching by default */
291
cache: boolean; // true
292
/** Default headers */
293
headers: {[key: string]: string};
294
/** Cross-domain detection */
295
crossDomain: boolean; // false
296
/** JSONP callback parameter name */
297
jsonp: string; // 'callback'
298
/** Accept headers for different data types */
299
accepts: {[key: string]: string};
300
}
301
```
302
303
**Usage Examples:**
304
305
```javascript
306
// Modify global settings
307
$.ajaxSettings.timeout = 10000; // 10 second default timeout
308
$.ajaxSettings.headers['X-Requested-With'] = 'XMLHttpRequest';
309
310
// Check active requests
311
console.log('Active requests:', $.active);
312
313
// Global error handling
314
$(document).ajaxError(function(event, xhr, settings, error) {
315
console.log('Ajax error:', error);
316
});
317
318
// Global success handling
319
$(document).ajaxSuccess(function(event, xhr, settings) {
320
console.log('Ajax success:', settings.url);
321
});
322
```
323
324
### Form Integration
325
326
Methods specifically designed for form handling.
327
328
```javascript { .api }
329
/**
330
* Serialize form data to URL-encoded string
331
* @returns Serialized form data
332
*/
333
$.fn.serialize();
334
335
/**
336
* Serialize form data to array of name/value objects
337
* @returns Array of {name, value} objects
338
*/
339
$.fn.serializeArray();
340
```
341
342
**Usage Examples:**
343
344
```javascript
345
// Serialize form for submission
346
$('#myForm').serialize();
347
// Result: "name=John&email=john%40example.com&age=30"
348
349
// Get form data as array
350
const formData = $('#myForm').serializeArray();
351
// Result: [
352
// {name: 'name', value: 'John'},
353
// {name: 'email', value: 'john@example.com'},
354
// {name: 'age', value: '30'}
355
// ]
356
357
// Submit form via Ajax
358
$('#myForm').on('submit', function(e) {
359
e.preventDefault();
360
$.post('/api/submit', $(this).serialize(), function(response) {
361
console.log('Form submitted:', response);
362
});
363
});
364
```
365
366
### Error Handling
367
368
Comprehensive error handling and status codes.
369
370
```javascript { .api }
371
// Error types passed to error callbacks:
372
// - 'timeout': Request timed out
373
// - 'error': General error
374
// - 'abort': Request aborted
375
// - 'parsererror': JSON/XML parsing failed
376
377
// HTTP status handling
378
$.ajax({
379
url: '/api/data',
380
statusCode: {
381
404: function() {
382
console.log('Page not found');
383
},
384
500: function() {
385
console.log('Server error');
386
}
387
}
388
});
389
```
390
391
### Request/Response Headers
392
393
Working with HTTP headers.
394
395
```javascript { .api }
396
// Set request headers
397
$.ajax({
398
url: '/api/data',
399
headers: {
400
'Authorization': 'Bearer token',
401
'Content-Type': 'application/json'
402
}
403
});
404
405
// Access response headers in success callback
406
$.ajax({
407
url: '/api/data',
408
success: function(data, status, xhr) {
409
const contentType = xhr.getResponseHeader('Content-Type');
410
const lastModified = xhr.getResponseHeader('Last-Modified');
411
console.log('Response headers:', contentType, lastModified);
412
}
413
});
414
```
415
416
### Performance and Best Practices
417
418
Optimizations and recommendations for Ajax usage:
419
420
```javascript
421
// Cache GET requests
422
$.ajaxSettings.cache = true;
423
424
// Use appropriate data types
425
$.getJSON('/api/data'); // Better than $.get with manual parsing
426
427
// Handle errors gracefully
428
$.ajax({
429
url: '/api/data',
430
timeout: 5000,
431
error: function(xhr, errorType) {
432
if (errorType === 'timeout') {
433
// Handle timeout specifically
434
}
435
}
436
});
437
438
// Abort requests when needed
439
const xhr = $.get('/long-request');
440
// Later...
441
xhr.abort();
442
443
// Use FormData for file uploads
444
const formData = new FormData($('#fileForm')[0]);
445
$.ajax({
446
url: '/upload',
447
type: 'POST',
448
data: formData,
449
processData: false,
450
contentType: false
451
});
452
```