AJAX (Asynchronous JavaScript and XML)
AJAX (Asynchronous JavaScript and XML) is a technique for creating more dynamic and responsive web applications. It enables the transfer of data between a web client (browser) and a web server without refreshing the entire page. This results in faster and more responsive web applications.
- AJAX is not a single technology but a combination of:
- HTML/XHTML for markup
- CSS for styling
- JavaScript for scripting
- DOM for manipulating HTML and CSS
- XML/JSON for data exchange
- XMLHttpRequest object for server communication
Key Characteristics
- Asynchronous: AJAX requests are asynchronous, meaning that the browser does not have to wait for the server response before continuing to execute other scripts. This allows the user to interact with the page while the request is being processed.
- Partial Update: AJAX allows you to update parts of a web page without reloading the entire page. This can improve the user experience by making the application more responsive.
- Data Exchange: While AJAX originally used XML, JSON is now commonly used due to its lighter weight and compatibility with JavaScript.
Fetch API
Modern browsers provide the Fetch API to make AJAX requests. The Fetch API is more powerful and flexible compared to the older XMLHttpRequest. This API allows configuring a new request by providing two parameters: the URL of the resource and an object containing the options for the request.
Basic Usage
Creating a Request
let myRequest = new Request('https://reqres.in/api/users/', {
method: 'POST',
body: JSON.stringify({ user: 'John Doe', job: 'unknown' }),
headers: { 'Content-Type': 'application/json' },
});
- URL: The resource's location (e.g., 'https://reqres.in/api/users/ (opens in a new tab)')
- Options: An object containing the request configuration (e.g., method, body, headers)
Fetching Data
The Fetch API returns a Promise that resolves to the Response object representing the response to the request. You can then extract the data from the response using the json()
method.
fetch(myRequest)
.then((response) => response.json())
.then((json) => {
console.log(json); // Parsed JSON response
});
fetch()
: Returns a promise that resolves with a response objectresponse.json()
: Reads the response stream and resolves with an object
Compressed Syntax
For more concise code, the configuration and fetch can be combined:
fetch('https://reqres.in/api/users/', {
method: 'POST',
body: JSON.stringify({ user: 'John Doe', job: 'unknown' }),
headers: { 'Content-Type': 'application/json' },
})
.then((response) => response.json())
.then((json) => {
console.log(json);
});
GET Request Example
For a simple GET request:
fetch('https://reqres.in/api/users/')
.then((response) => response.json())
.then((json) => {
console.log(json);
});
Handling Errors
To handle fetch failures, add a catch
statement. However, this won't catch errors if the connection was successful but the response status indicates an error (e.g., 404 or 500). Use response.ok
to check if the status code is in the 200 range:
fetch('https://reqres.in/api/unknown/23')
.then((response) => {
return response.ok ? response.json() : Promise.reject(response.status);
})
.then((json) => {
console.log(json);
})
.catch((err) => {
console.log(`Error: ${err}`); // Logs error status
});
response.ok
: True if the response status is in the 200 range.Promise.reject
: Handles non-200 status codes.