0% found this document useful (0 votes)
8 views9 pages

AJAX

AJAX (Asynchronous JavaScript and XML) is a web development technique that allows web pages to send and receive data asynchronously without reloading the entire page, enhancing user experience and reducing load times. It combines technologies like HTML, CSS, JavaScript, and typically JSON for efficient data handling. AJAX is widely used in modern web applications for features such as live search, real-time updates, and dynamic content loading.

Uploaded by

mr.dhanush.j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

AJAX

AJAX (Asynchronous JavaScript and XML) is a web development technique that allows web pages to send and receive data asynchronously without reloading the entire page, enhancing user experience and reducing load times. It combines technologies like HTML, CSS, JavaScript, and typically JSON for efficient data handling. AJAX is widely used in modern web applications for features such as live search, real-time updates, and dynamic content loading.

Uploaded by

mr.dhanush.j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

AJAX (Asynchronous JavaScript and XML)

Introduction:

AJAX (Asynchronous JavaScript and XML) is a web development technique that enables
web pages to send and receive data from a server asynchronously—without reloading the entire
page. Originally introduced by Microsoft in 1999 through the XMLHttpRequest object in
Internet Explorer 5, it allowed dynamic content updates in the background. The term "AJAX"
was popularized in 2005 by Jesse James Garrett, describing a combination of HTML, CSS,
JavaScript, and XML (now mostly replaced by JSON) to create faster, interactive web
applications. Today, AJAX forms the backbone of modern web interactivity and is widely used
in frameworks and APIs like Fetch, Axios, and jQuery.

What is Ajax?

 AJAX stands for Asynchronous JavaScript and XML.


 It is not a programming language, but a web development technique used to create
faster, better, and more dynamic web applications.
 AJAX enables a web page to send and receive data asynchronously—in the
background—without having to reload the entire page. This allows specific parts of
the page to be updated dynamically in response to user interactions (like clicking a
button), resulting in a smoother and more efficient user experience.

Technologies Used in AJAX

AJAX works by combining several core web technologies:

1. HTML (Hypertext Markup Language) – Defines the structure of the web


application.

2. CSS (Cascading Style Sheets) – Provides the styling and layout of the web
application.

3. JavaScript – Enables interactivity and handles the asynchronous communication


between the client and the server.

1|Page
4. XML (Extensible Markup Language) – Originally used to store and transport
data from the web server. (Note: Today, JSON is more commonly used due to its
simplicity and compatibility with JavaScript.)

What's the meaning of Asynchronous in AJAX?

Asynchronous means that the the Web Application could send and receive data from the Web
Server without refreshing the page. This background process of sending and receiving data
from the server along with updating different sections of a web page defines Asynchronous
property/feature of AJAX.

Key Benefits of Using Ajax

1. Reduced Page Load Time: By updating only parts of the page instead of reloading the
entire page, Ajax significantly reduces the load time.

2. Enhanced User Experience: Users can continue interacting with the web page while
data is being fetched or sent, leading to a smoother experience.

3. Efficient Data Transmission: Ajax requests typically send and receive smaller
amounts of data compared to full page reloads, making interactions faster and reducing
server load.

Basic Workflow of AJAX

AJAX enables dynamic communication between a web page and a web server without
refreshing the whole page. The process follows these core steps:

1. User Interaction

➤ A user performs an action on the webpage (e.g., clicks a button or submits a form).

2. AJAX Request Initiated

➤ JavaScript captures the event and uses the browser's built-in XMLHttpRequest
object to send an asynchronous request to the server.

3. Server-Side Processing

2|Page
➤ The web server receives the request, processes it, and sends back a response. The
response is usually in JSON, XML, or HTML format.

4. DOM Update

➤ JavaScript receives the response and updates the relevant part of the webpage using
the HTML DOM (Document Object Model)—without reloading the entire page.

5. Key Components Used

 XMLHttpRequest Object

➤ A JavaScript API used to send and receive data asynchronously between the
web browser and the server. It provides methods like .open() and .send() to make
HTTP requests.

 HTML DOM

➤ When a webpage loads, the browser creates a Document Object Model


(DOM)—a structured representation of the HTML content. AJAX uses JavaScript
to manipulate this DOM and display updated content dynamically.

3|Page
Programming in AJAX

Creating a XMLHttpRequest Object in JavaScript:

To make an AJAX call, we first create an instance of the XMLHttpRequest object:

Javascript:

var xhttp = new XMLHttpRequest();

This object allows JavaScript to communicate with the server without reloading the entire web
page.

Important Properties of XMLHttpRequest

 readyState: Indicates the current state of the request.

Value Meaning
0 Request not initialized
1 Server connection established
2 Request received
3 Processing request

 onreadystatechange: Defines a callback function that is triggered every time


readyState changes. You use this to check if the request is complete and successful.

 status: Indicates the HTTP status code of the response.

Common Status Code Meaning


200 OK (Success)
403 Forbidden
404 Not Found
500 Internal Server Error

4|Page
Commonly Used Methods of XMLHttpRequest :
To send a request to the server, use the following methods:
1. open(method, url, async) – Prepares the request.
 This method sets up the request before it is sent using send(). It does not actually
send the request — it just prepares it.
 method (String):
Specifies the HTTP method used to make the request.
Common methods include:
o "GET" – Requests data from the server (data is sent in the URL).
o "POST" – Sends data to the server (used for submitting form data).
o "PUT" – Updates data on the server.
o "DELETE" – Deletes data from the server.
 url (String):
o Defines the location of the server resource (a file or API endpoint) that
will handle the request.
o It can be a local file ("file.txt") or a server endpoint ("server.php" or
"https://example.com/api").
 async (Boolean):
o Determines whether the request is sent asynchronously (true) or
synchronously (false).
o true (default): The script continues to run while the request is being
processed. Recommended for non-blocking operations.
o false: The script waits (blocks) until the request is completed before
continuing. Rarely used today due to UI freezing.
2. send() – Sends the request to the server.
 Purpose: Sends the request to the server after open() is called.
 Use:
o send() with no argument for GET requests.
o send(data) with data (like form input) for POST requests.
Example:
Javascript:
xhttp.open("GET", "data.php", true);

xhttp.send();

5|Page
Before using the open() and send() methods in AJAX, we must first check the status of
the request using the onreadystatechange property of the XMLHttpRequest object. This
function is called automatically whenever the readyState of the request changes. Inside it, we
check if readyState == 4 (which means the request is complete) and status == 200 (which means
the request was successful). Only when both conditions are true, we write our logic — usually
to update the webpage with the response from the server. After setting this up, we use the
open(method, url, async) method to prepare the request and the send() method to send it to the
backend server (like a PHP file).

Example:
Javascript:

function fetchData() {

// Step 1: Create a new XMLHttpRequest object

var request = new XMLHttpRequest();

// Step 2: Define the callback function to handle response

request.onreadystatechange = function() {

// Check if the request is complete and successful

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

// Step 3: Write your logic to handle the response

document.getElementById("output").innerHTML = this.responseText;

};

// Step 4: Open the request (method, URL, async true/false)

request.open("GET", "yourfile.php", true); // You can also use "POST" and a different URL

// Step 5: Send the request

request.send();

6|Page
Example:

index.html:

<!DOCTYPE html>
<html>
<head>
<title>AJAX with PHP Example</title>
</head>
<body>
<div id="foo">
<h2>Click the Button to Load Content from PHP</h2>
<button type="button" onclick="changeContent()">Change Content</button>
</div>
<script>
function changeContent() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Update the page with the response
document.getElementById("foo").innerHTML = this.responseText;
}
};
// Asynchronous GET request to the PHP file
xhttp.open("GET", "data.php", true);
xhttp.send();
}
</script>
</body>
</html>

7|Page
data.php:

<?php

// You can fetch data from a database here if needed

echo "<h2>This content was loaded from a PHP file using AJAX!</h2>";

echo "<p>AJAX allows partial updates without refreshing the page.</p>";

?>

Handling Different Response Types


AJAX allows responses in multiple data formats, not just plain text:
 Text (responseText): Most commonly used. Useful for inserting HTML or simple
text.
 XML (responseXML): Used when the server sends structured XML data.
 JSON (parsed using JSON.parse()): Lightweight and widely used for structured data
exchange.
JSON is now preferred over XML because it is easier to parse and more
readable.
Real-Time Use Cases of AJAX
AJAX is ideal for features that require partial page updates:
 Live Search suggestions (Google search bar)
 Real-time form validation
 Chat applications (loading messages without refreshing)
 Dashboard updates (e.g., stock prices or weather)
 "Load More" buttons in blogs or social media
Drawbacks of AJAX
While powerful, AJAX also has some limitations:
 SEO Issues: Search engines may not index dynamically loaded content.
 Browser Dependency: Older browsers may not fully support AJAX features.
 Complexity: Managing multiple AJAX calls and callbacks can become messy.
 Security: Can expose endpoints if not properly protected.
Modern Alternatives to XMLHttpRequest
Though XMLHttpRequest is still widely used in theory, modern development often prefers:

8|Page
1. Fetch API – Simpler syntax, Promise-based, and more powerful.
2. Axios (Library) – Easy to use, supports promises, interceptors, and more.
Advantages of Using AJAX in Programming
1. No Page Reload
o AJAX sends and receives data without refreshing the whole page.
2. Faster Updates
o Only parts of the page are updated, so it works quickly.
3. Smooth Experience
o Users can keep using the page while data loads in the background.
4. Less Server Work
o It sends only needed data, saving server time and internet data.
5. Live Content Updates
o Useful for updating things like chat messages or search results without
reloading.
6. Works Everywhere
o Uses common web tech like HTML, CSS, and JavaScript, and works with any
backend like PHP, Python, etc.
7. Connects to Server Easily
o Can fetch or send data from various server files or APIs.
8. Good for Real-Time Apps
o Perfect for apps that need to update often, like weather or stock sites.
9. Faster Communication
o Less waiting time because only small data is exchanged.
10. Flexible for Developers
o Developers can control how data is sent, received, and shown on the page.

9|Page

You might also like