Performs an asynchronous HTTP (Ajax) request using the Fetch API.
$.ajax({
url: '/api/users',
method: 'GET',
dataType: 'json',
data: { page: 1, limit: 10 }
})
.then(response => {
console.log('Success:', response);
})
.catch(error => {
console.error('Request failed:', error);
})
.finally(() => {
console.log('Cleanup actions');
});
// Console Output (JSON Object)
{
"page": 1,
"users": [...]
}
$.ajax({
url: '/api/save',
method: 'POST',
contentType: 'application/json',
data: { name: 'John', age: 30 }
})
.then(data => console.log('Saved:', data))
.catch(err => console.error(err));
// Network Request Payload
{
"name": "John",
"age": 30
}
// Assuming a file input on the page: <input type="file" id="fileUpload">
const fileInput = $('#fileUpload')[0];
const formData = new FormData();
formData.append('file', fileInput.files[0]);
$.ajax({
url: '/upload',
method: 'POST',
processData: false,
contentType: false,
data: formData
})
.then(res => console.log('Uploaded'))
.catch(err => console.error('Upload failed'));
// Sends multipart/form-data request to /upload
The method accepts a configuration object with the following properties:
| Property | Type | Description |
|---|---|---|
| url | string | The URL to request. Required. |
| method | string | HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE'). Default is 'GET'. |
| data | object | string | FormData | Data to send. Converted to query string for GET, or body for POST. Supports nested objects and arrays. |
| dataType | string | Expected response type ('json', 'text', 'html', 'script'). Default is 'text'. |
| headers | object | Additional HTTP headers to send. |
| contentType | string | boolean | Content-Type header value. Set to false for FormData. Default: 'application/x-www-form-urlencoded; charset=UTF-8'. |
| processData | boolean | Whether to process the data object into a query string. Set to false when sending FormData or Blob. Default: true. |
| cache | boolean | Whether to allow caching for GET requests. If false, adds a timestamp. Default: true. |
| timeout | number | Request timeout in milliseconds. Default: 0 (no timeout). |
| crossDomain | boolean | If true, forces cross-domain request behavior (e.g., no X-Requested-With). If undefined, it is auto-detected. |
| xhrFields | object | Options for the underlying request. Cookies are sent by default for same-origin requests. Use { withCredentials: true } for cross-origin. |
Returns: A Promise that resolves with the response data or rejects with an error.