AJAX Intro


AJAX stands for Asynchronous JavaScript and XML. It is not a programming language, but a technique that allows web pages to communicate with the server without reloading the entire page.

With AJAX, you can request data from the server, receive a response, and update parts of a web page dynamically. This improves user experience by making web applications faster, smoother, and more interactive.

How AJAX Works

AJAX uses a combination of:

  • JavaScript – To send requests and handle responses asynchronously.

  • XMLHttpRequest (XHR) object – Core of AJAX for communicating with the server.

  • HTML/CSS – To display content on the page.

  • Server-side scripts (PHP, Node.js, etc.) – To process requests and return data, usually in XML, JSON, or plain text.

The basic workflow:

  1. A user triggers an event (like clicking a button).

  2. JavaScript creates an XMLHttpRequest object.

  3. The request is sent to the server asynchronously.

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

  5. JavaScript receives the response and updates the web page dynamically.

Example: Basic AJAX Request

Here’s a simple example to demonstrate how AJAX works:

HTML File: index.html

<!DOCTYPE html>
<html>
<head>
  <title>AJAX Intro Example</title>
  <script>
    function fetchMessage() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "message.php", true);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          document.getElementById("result").innerHTML = xhr.responseText;
        }
      };
      xhr.send();
    }
  </script>
</head>
<body>
  <h2>AJAX Demo</h2>
  <button onclick="fetchMessage()">Get Message</button>
  <div id="result" style="margin-top:20px;"></div>
</body>
</html>

PHP File: message.php

<?php
echo "Hello! This message was fetched using AJAX.";
?>

Explanation

  • The XMLHttpRequest object handles the AJAX request.

  • xhr.open("GET", "message.php", true) sets the request method and URL.

  • xhr.onreadystatechange monitors changes in the request state.

  • When readyState is 4 (request finished) and status is 200 (success), the response is displayed in the div with id="result".

Clicking the button fetches the message without reloading the page.

AJAX States

The readyState property of XMLHttpRequest shows the current state of the request:

Value State
0 Request not initialized
1 Server connection established
2 Request received
3 Processing request
4 Request finished and response ready

Advantages of AJAX

  1. Faster user experience – Only part of the page updates, not the entire page.

  2. Reduced server load – Smaller requests compared to full page reloads.

  3. Dynamic content – Pages can respond instantly to user actions.

  4. Smooth interactions – Makes web apps behave more like desktop applications.

Common Uses of AJAX

  • Live search suggestions

  • Form validation without page reload

  • Loading new content dynamically (e.g., news feeds, comments)

  • Real-time notifications

  • Polls and surveys

  • Updating tables or dashboards dynamically

GET vs POST in AJAX

AJAX supports GET and POST methods:

  • GET: Requests data from the server. Parameters are appended to the URL. Best for fetching data.

  • POST: Sends data to the server securely in the request body. Best for submitting forms.

Example using POST:

var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("result").innerHTML = xhr.responseText;
  }
};
xhr.send("name=Sunita&age=25");

AJAX with JSON

Although AJAX originally used XML, modern applications often use JSON because it’s easier to work with in JavaScript.

PHP (data.php)

<?php
$data = array("name" => "Sunita", "age" => 25, "course" => "Web Development");
echo json_encode($data);
?>

JavaScript

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var obj = JSON.parse(xhr.responseText);
    document.getElementById("result").innerHTML = 
      "Name: " + obj.name + ", Age: " + obj.age + ", Course: " + obj.course;
  }
};
xhr.send();

JSON allows you to send structured data efficiently and access it easily in JavaScript.

Handling Errors in AJAX

It’s important to handle errors:

xhr.onerror = function() {
  alert("Request failed. Please try again.");
};

You can also check xhr.status to handle server errors (like 404 or 500).

Summary of the Tutorial

AJAX is a powerful technique that allows web pages to interact with servers dynamically without reloading.

Key points:

  • AJAX uses JavaScript and XMLHttpRequest to communicate asynchronously.

  • It improves speed, user experience, and interactivity.

  • Data can be returned in text, XML, or JSON format.

  • It’s widely used for live search, dynamic content, form validation, and real-time updates.

  • GET and POST methods determine how data is sent or received.

Understanding AJAX is the foundation for building modern, responsive web applications.


Practice Questions

  1. Create a simple HTML page with a button that fetches a message from a PHP file using AJAX and displays it in a div.

  2. Modify the previous example to fetch the current server time instead of a static message.

  3. Create a form with a single input field. Use AJAX to send the input value to a PHP file and return a greeting message.

  4. Create an HTML page with two buttons: one that fetches data using GET and another using POST. Display the responses in separate div elements.

  5. Write a PHP file that returns a JSON object with a user’s name, age, and course. Use AJAX to fetch this data and display it dynamically.

  6. Create a page that uses AJAX to fetch a random quote from a PHP file every 5 seconds without reloading the page.

  7. Implement error handling in an AJAX request. Display an alert if the request fails.

  8. Create a dropdown menu with three options. Use AJAX to send the selected option to the server and display a relevant message.

  9. Modify the message-fetching example to show a “Loading…” text while waiting for the server response.

  10. Create a small page that uses AJAX to fetch content from different PHP files dynamically when clicking multiple buttons (e.g., “About”, “Contact”, “Services”).


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top