← Back to Index

$.ajax()

Performs an asynchronous HTTP (Ajax) request using the Fetch API.

Examples

1. Basic GET Request

$.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');
});

Result

// Console Output (JSON Object)
{
     "page": 1,
     "users": [...]
}

2. POST Request with JSON Data

$.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));

Result

// Network Request Payload
{
     "name": "John",
     "age": 30
}

3. POST Request with FormData (File Upload)

// 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'));

Result

// Sends multipart/form-data request to /upload

Parameters

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.