Async

JS AJAX

AJAX with XMLHttpRequest

JavaScript AJAX uses XMLHttpRequest for server requests, kept minimal.

Introduction to AJAX

AJAX (Asynchronous JavaScript and XML) is a web technology that allows you to update parts of a web page without reloading the entire page. It uses the XMLHttpRequest object to send and receive data between a web browser and a server asynchronously.

Setting Up XMLHttpRequest

The XMLHttpRequest object is the core of AJAX operations. It provides a way to interact with servers via HTTP requests. Below is a simple example of setting up an XMLHttpRequest object:

Making a GET Request

To make a GET request, you need to initialize the request by calling the open method, specify the HTTP method ('GET') and the URL of the resource:

The third parameter true makes the request asynchronous. After opening the connection, you can send the request using the send method:

Handling the Response

Once the request completes, you can handle the response in the onreadystatechange event handler. This handler checks if the request is complete and the response is successful:

Error Handling in AJAX

Error handling is crucial in AJAX requests. You can handle errors by checking the status code or using the onerror event:

Making a POST Request

To send data to the server with a POST request, you need to set the request header Content-Type and include the data in the send method:

Conclusion

Using AJAX with XMLHttpRequest allows for efficient data retrieval and updates without page reloads. Though modern alternatives like Fetch API exist, understanding AJAX provides foundational knowledge for handling asynchronous operations in JavaScript.

Previous
Fetch API