Ajax
Ajax Service
Purpose
The ajax function performs HTTP requests (GET, POST, PUT, PATCH, DELETE) and handles responses or errors.
Parameters
- url (String): The URL to which the request is made.
- options (RequestOptions | null): An optional configuration object for the request. If not provided,
defaultoptions are used.
Request Option Types
| Action | Description |
|---|---|
params | Data sent with the request (for POST, PUT, etc.). Default is null. |
method | HTTP method to use ('get' |
query | Query parameters for GET requests. Default is null. |
headers | Custom headers for the request. Default is null. |
showNotifications | Flag to show notifications. Default is true. |
showLoadingIndicator | Flag to show loading indicator. Default is true. |
severity | Severity of the error for logging purposes. Default is null. |
debug | Flag to enable debug mode. Default is false. |
timeout | Timeout for the request in milliseconds. Default is 30000 (30 seconds). |
Behavior
- GET Requests: Appends query parameters to the URL.
POST/PUT/PATCH/DELETERequests: Sends params as the body of the request.- Default request headers are set to
{'accept': 'application/json'}if no custom headers are provided.
Error Handling
- If the request fails, the
errorHandlerfunction is called with the error details. - Logs and handles errors based on the
severityandadditionaldetails.
Responses
- On success: Returns an object with success:
trueand thedatareceived. - On failure: Returns an object with success:
false,error details, anderror data(if available).
Default Values
- If no options are provided, defaults are set (e.g., GET method, 30-second timeout, notifications enabled).
const response = await ajax('/api/data', {
method: 'get',
query: { key: 'value' },
showNotifications: true
});