Professional Documents
Culture Documents
Ajax
Ajax
Ajax
a. XMLHttpRequest Object:
The XMLHttpRequest object is a key component of AJAX. It enables communication between the
web browser and the server. You can use it to send requests to the server and handle the responses.
b. Callback Functions:
AJAX relies on callback functions to handle responses asynchronously. These functions are executed
when the server responds to the request.
The open method initializes the request. The parameters are the HTTP method (GET or POST), the
server URL, and a boolean indicating whether the request should be asynchronous.
xhttp.onreadystatechange = function () {
console.log(this.responseText);
};
The onreadystatechange event is triggered when the state of the request changes. The condition
checks if the request is complete (readyState == 4) and successful (status == 200).
xhttp.send();
This sends the request to the server. For a POST request, you can send data along with the request
using the send method.
3. Handling Different Types of Requests:
a. GET Request:
xhttp.send();
b. POST Request:
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("key1=value1&key2=value2");
4. Handling Responses:
The server response can be HTML, XML, JSON, or any other format. You can parse and use the
response data accordingly.
Example:
xhttp.onreadystatechange = function () {
console.log(responseData);
};
xhttp.send();
This example makes a GET request to the JSONPlaceholder API and logs the response data.