JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript AJAX Introduction


Modern websites don’t just reload the entire page every time new data is needed. Instead, they can load data from a server in the background and update part of the web page dynamically.

This smooth, interactive experience is made possible by AJAX — one of the most important features in web development.

What Is AJAX?

AJAX stands for Asynchronous JavaScript and XML.

It is not a programming language, but a set of web technologies that work together to send and receive data from a web server without reloading the page.

In simple terms:
AJAX allows your webpage to talk to the server and update parts of the page instantly — just like how chat apps, weather widgets, or live search boxes work.

What Does “Asynchronous” Mean?

Asynchronous means the browser doesn’t wait for the server response to continue running other code.

For example:

  • You send a request to the server.

  • While waiting for the data, the rest of your page continues working.

  • When the server responds, JavaScript updates the page content dynamically.

This makes the user experience faster and smoother.

How AJAX Works

AJAX uses a combination of web technologies:

Technology Role
HTML/CSS To display the page and style it
JavaScript To make the AJAX request
XMLHttpRequest (XHR) To communicate with the server
JSON or XML To receive and process the server response
PHP / ASP / Node.js To handle server-side processing

AJAX Workflow

Here’s how the AJAX process works step by step:

  1. An event occurs in the browser (like a button click).

  2. JavaScript creates an XMLHttpRequest object.

  3. The request is sent to the server.

  4. The server processes the request and sends a response.

  5. JavaScript receives the response.

  6. The web page updates dynamically — without reloading.

Diagrammatically:

User Action → JavaScript → Server Request → Server Response → Update Page

Real-World Examples of AJAX

You use AJAX every day, often without realizing it:

  • Google Search Suggestions: Results appear as you type.

  • Chat Applications: Messages appear instantly.

  • Weather Updates: Data refreshes without reloading.

  • Form Submissions: Sent in the background without page refresh.

  • E-commerce Filters: Products update when filters are applied.

Example: Without AJAX (Traditional Way)

In a normal (non-AJAX) web app, clicking a button that loads data causes the entire page to reload.

<!-- Clicking this button reloads the page -->
<form action="data.php" method="GET">
  <button type="submit">Load Data</button>
</form>

Drawback: Every request reloads the whole page, which is slow and inefficient.

Example: With AJAX

Using AJAX, you can load data dynamically without reloading the page.

HTML File

<button id="loadBtn">Load Data</button>
<div id="result"></div>

<script>
document.getElementById("loadBtn").addEventListener("click", loadData);

function loadData() {
  // 1. Create an XMLHttpRequest object
  const xhr = new XMLHttpRequest();

  // 2. Open a request
  xhr.open("GET", "data.txt", true);

  // 3. Handle the response
  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("result").textContent = xhr.responseText;
    } else {
      document.getElementById("result").textContent = "Error loading data";
    }
  };

  // 4. Send the request
  xhr.send();
}
</script>

Explanation:

  • When the button is clicked, loadData() runs.

  • XMLHttpRequest is created and sends a request to data.txt.

  • The page updates only the <div> with new data — no reload.

Understanding XMLHttpRequest

The XMLHttpRequest (XHR) object is the core of AJAX.

Main Properties:

Property Description
readyState Current state of the request (0–4)
status HTTP status code (e.g., 200 = OK)
responseText The response data as a string

readyState Values:

Value State Meaning
0 UNSENT Request not initialized
1 OPENED Request created
2 HEADERS_RECEIVED Response headers received
3 LOADING Loading response data
4 DONE Request finished and response is ready

AJAX Using JSON

Today, JSON is used more often than XML because it’s lightweight and easy to read.

Example: Fetch JSON Data

<button id="getUser">Get User</button>
<div id="userInfo"></div>

<script>
document.getElementById("getUser").addEventListener("click", function() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "user.json", true);

  xhr.onload = function() {
    if (xhr.status === 200) {
      const user = JSON.parse(xhr.responseText); // Convert JSON to JS object
      document.getElementById("userInfo").innerHTML =
        `<p>Name: ${user.name}</p><p>Age: ${user.age}</p>`;
    }
  };
  
  xhr.send();
});
</script>

user.json

{
  "name": "Vicky",
  "age": 28
}

Explanation:

  • XMLHttpRequest fetches the JSON file.

  • JSON.parse() converts JSON data into a JavaScript object.

  • Data is displayed on the page without reloading.

Advantages of AJAX

Advantage Description
Faster Updates Only parts of the page are updated.
Better UX Smoother and more interactive experience.
Reduced Bandwidth Less data is sent between client and server.
Asynchronous Doesn’t block page rendering.
Reusable Can use with any server-side language (PHP, ASP, Node, etc.).

Disadvantages of AJAX

Limitation Description
Browser Compatibility Older browsers may not fully support XHR.
No Browser History Back/forward buttons may not work as expected.
Security Issues AJAX can expose data if not properly secured.
SEO Challenges Search engines might not index AJAX-loaded content.

Real-World Use Case Example

Imagine you have a comment section.
With AJAX, users can submit comments, and they instantly appear without refreshing the page.

That’s how modern social media apps like Facebook and YouTube work behind the scenes.

Summary of the Tutorial

The AJAX technique makes web applications faster, smoother, and more interactive by updating only the necessary parts of a page.

Key takeaways:

  • AJAX stands for Asynchronous JavaScript and XML.

  • It allows data exchange with the server in the background.

  • Core component: XMLHttpRequest (XHR).

  • Commonly uses JSON for data.

  • Works with any server-side technology (PHP, ASP, Node.js, etc.).

With AJAX, you can create real-time and dynamic web apps that feel modern and responsive.


Practice Questions

  1. Write a JavaScript function using XMLHttpRequest to fetch a text file (data.txt) and display its content inside a <div> with id "output" when a button is clicked.

  2. Create an AJAX request and display one of the following messages based on the response status: "Data Loaded Successfully" for status 200, "File Not Found" for status 404, and "Server Error" for any other response.

  3. Modify your AJAX code to display "Loading..." in the page before the request completes, and replace it with the actual response once it’s done.

  4. Fetch data from a file named info.json and display user details (name, email, age) dynamically in a web page using JavaScript DOM methods.

  5. When a request is sent, disable the button (Load Data). Re-enable it after the data loads successfully.

  6. Create an AJAX function that shows a custom error message if the server returns any response other than status 200.

  7. Load partial HTML data (like a paragraph) from a file named about.html and insert it only into the <section id="aboutSection"> without affecting other parts of the page.

  8. Create two buttons — one loads students.txt and another loads teachers.txt. Use one function to handle both requests based on which button is clicked.

  9. Fetch a JSON array containing multiple user objects and display them in a list format (like name and age). Example JSON:

[
  {"name": "Vicky", "age": 25},
  {"name": "Sanjana", "age": 26}
]
  1. Write code that logs errors (like 404 or 500) in the browser console using console.error() when the AJAX request fails.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top