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 Examples


AJAX allows web pages to communicate with the server without reloading, which is useful for building interactive web applications. In this tutorial, we’ll look at multiple practical examples of AJAX in action.

For instance, Vicky can create different features where Sanjana interacts with the page, and data updates dynamically.

Example 1: Fetching a Greeting

A simple AJAX example is fetching a greeting from the server.

PHP File (greet.php)

<?php
header('Content-Type: text/plain');
echo "Hello, Sanjana! Welcome to AJAX examples.";
?>

HTML and JavaScript

<button id="greetBtn">Get Greeting</button>
<div id="greetOutput"></div>

<script>
document.getElementById("greetBtn").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "greet.php", true);

  xhr.onload = function() {
    if(xhr.status === 200) {
      document.getElementById("greetOutput").textContent = xhr.responseText;
    } else {
      document.getElementById("greetOutput").textContent = "Error fetching greeting";
    }
  };

  xhr.send();
});
</script>

Explanation:

  • The PHP script returns a plain text greeting.

  • Clicking the button fetches the greeting dynamically and displays it in the <div>.

Example 2: Sending Form Data

AJAX allows forms to submit data without reloading the page.

HTML Form

<input type="text" id="name" placeholder="Enter your name">
<button id="sendBtn">Send</button>
<div id="formResponse"></div>

JavaScript

document.getElementById("sendBtn").addEventListener("click", function() {
  let name = document.getElementById("name").value;

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "process.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function() {
    if(xhr.status === 200) {
      document.getElementById("formResponse").textContent = xhr.responseText;
    } else {
      document.getElementById("formResponse").textContent = "Error sending data";
    }
  };

  xhr.send("username=" + encodeURIComponent(name));
});

PHP File (process.php)

<?php
if(isset($_POST['username'])){
    $name = htmlspecialchars($_POST['username']);
    echo "Hello, $name! Your data has been received.";
} else {
    echo "No data received.";
}
?>

Explanation:

  • AJAX sends the form data using POST.

  • PHP processes the input and returns a response.

  • The page does not reload, keeping the interaction smooth.

Example 3: Fetching JSON Data

AJAX can fetch JSON data and display it dynamically.

PHP File (user.php)

<?php
header('Content-Type: application/json');

$user = array(
  "name" => "Sanjana",
  "age" => 26,
  "email" => "sanjana@example.com"
);

echo json_encode($user);
?>

JavaScript

let xhr = new XMLHttpRequest();
xhr.open("GET", "user.php", true);

xhr.onload = function() {
  if(xhr.status === 200) {
    let user = JSON.parse(xhr.responseText);
    document.getElementById("output").innerHTML =
      `Name: ${user.name}<br>Age: ${user.age}<br>Email: ${user.email}`;
  } else {
    document.getElementById("output").textContent = "Failed to load data";
  }
};

xhr.send();

Explanation:

  • PHP returns JSON data.

  • JavaScript parses it and displays user information dynamically.

Example 4: Live Search

Live search is a popular AJAX use case.

HTML

<input type="text" id="search" placeholder="Search users">
<div id="results"></div>

JavaScript

document.getElementById("search").addEventListener("keyup", function() {
  let query = this.value;

  if(query.length === 0) {
    document.getElementById("results").innerHTML = "";
    return;
  }

  let xhr = new XMLHttpRequest();
  xhr.open("GET", "search.php?q=" + encodeURIComponent(query), true);

  xhr.onload = function() {
    if(xhr.status === 200) {
      document.getElementById("results").innerHTML = xhr.responseText;
    } else {
      document.getElementById("results").textContent = "Error fetching results";
    }
  };

  xhr.send();
});

Explanation:

  • The input field sends queries to PHP as the user types.

  • PHP returns matching results, displayed dynamically in the <div>.

Example 5: Dynamic Content Loading

AJAX can fetch and display content dynamically on demand.

HTML

<button id="loadPosts">Load Posts</button>
<div id="posts"></div>

JavaScript

document.getElementById("loadPosts").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "posts.php", true);

  xhr.onload = function() {
    if(xhr.status === 200) {
      document.getElementById("posts").innerHTML = xhr.responseText;
    } else {
      document.getElementById("posts").textContent = "Failed to load posts";
    }
  };

  xhr.send();
});

Explanation:

  • Clicking the button fetches server content via AJAX.

  • Content is displayed in the <div> without reloading the page.

Benefits of AJAX Examples

  • Improves user experience with fast, interactive interfaces.

  • Reduces page reloads, making websites smoother.

  • Allows real-time updates like live search and chat.

  • Works with different types of responses: text, HTML, JSON.

Vicky can implement multiple features, and Sanjana will experience instant updates and smoother interactions without waiting for full page reloads.

Summary of the Tutorial

AJAX examples show how to:

  • Fetch text, HTML, or JSON dynamically.

  • Submit forms without refreshing the page.

  • Implement live search for instant results.

  • Load content dynamically on user actions.

Using these examples, developers can build responsive, interactive web applications that make users like Sanjana enjoy real-time updates and seamless interactions.


Practice Questions

  1. Write an AJAX GET request to fetch a greeting from greet.php and display it in a <div> when a button is clicked.

  2. Create a form to submit a name via AJAX POST to process.php and display the response without reloading the page.

  3. Fetch JSON data from user.php and display Sanjana’s name, age, and email dynamically.

  4. Build a live search input that sends queries to search.php and displays matching results in a <div>.

  5. Create a button that loads posts from posts.php via AJAX GET and displays them dynamically in a <div>.

  6. Write an AJAX request that fetches user data and populates an HTML table with name and email.

  7. Create a function to send feedback via AJAX POST to feedback.php and display a confirmation message.

  8. Write an AJAX GET request that automatically refreshes notifications every 5 seconds and updates a <div>.

  9. Build a simple chat interface where messages are sent via AJAX POST to send_message.php and fetched periodically from get_messages.php.

  10. Create an AJAX request to filter users by age and dynamically display only users older than 25 in a <div>.


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