Ajax

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Here's a basic overview of how AJAX works and how you can use it:

1. Understanding AJAX Components:

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.

Making a Simple AJAX Request:

a. Creating an XMLHttpRequest Object:

var xhttp = new XMLHttpRequest();

b. b. Configuring the Request:

xhttp.open("GET", "your_server_url", true);

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.

c. Handling the Response:

xhttp.onreadystatechange = function () {

if (this.readyState == 4 && this.status == 200) {

// Code to handle the response

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

d. Sending the Request:

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.open("GET", "your_server_url", true);

xhttp.send();

b. POST Request:

xhttp.open("POST", "your_server_url", true);

// Set the content type for a POST request

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// Include the data to be sent with the request

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:

var xhttp = new XMLHttpRequest();

xhttp.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);

xhttp.onreadystatechange = function () {

if (this.readyState == 4 && this.status == 200) {

var responseData = JSON.parse(this.responseText);

console.log(responseData);

};

xhttp.send();

This example makes a GET request to the JSONPlaceholder API and logs the response data.

You might also like