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 Applications


AJAX allows web pages to communicate with the server without reloading, making them faster and more interactive. Using AJAX, you can build real-world applications that respond to user actions immediately, enhancing user experience.

For example, Vicky can create applications where Sanjana interacts with the interface, and the data updates dynamically.

What Are AJAX Applications?

AJAX applications are web applications that use asynchronous requests to fetch or send data from the server without refreshing the page. Examples include:

  • Live search: Search suggestions appear as the user types.

  • Chat applications: Messages appear instantly without page reload.

  • Content feeds: News feeds or posts load dynamically.

  • Form submissions: Users submit forms and receive instant confirmation.

  • Data dashboards: Charts and tables update in real time.

AJAX separates client-side and server-side operations, making the application more efficient and responsive.

Example 1: Live Search

A live search application shows results as the user types, without waiting for a page reload.

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();
});

PHP File (search.php)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$query = $_GET['q'];
$sql = "SELECT name, email FROM users WHERE name LIKE '%$query%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<p>Name: ".$row['name'].", Email: ".$row['email']."</p>";
    }
} else {
    echo "No results found";
}

$conn->close();
?>

Explanation:

  • The search input sends queries to PHP via AJAX.

  • PHP fetches matching users from the database.

  • Results are displayed dynamically in the <div> as Sanjana types.

Example 2: Chat Application

AJAX allows chat messages to be sent and received without page reload.

HTML

<div id="chatBox"></div>
<input type="text" id="message" placeholder="Type a message">
<button id="send">Send</button>

JavaScript

function loadMessages() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "get_messages.php", true);

  xhr.onload = function() {
    if(xhr.status === 200) {
      document.getElementById("chatBox").innerHTML = xhr.responseText;
    }
  };

  xhr.send();
}

// Load messages every 3 seconds
setInterval(loadMessages, 3000);

document.getElementById("send").addEventListener("click", function() {
  let msg = document.getElementById("message").value;

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

  xhr.onload = function() {
    if(xhr.status === 200) {
      document.getElementById("message").value = "";
      loadMessages(); // Refresh chat
    }
  };

  xhr.send("message=" + encodeURIComponent(msg));
});

Explanation:

  • Messages are sent to the server using POST.

  • Chat history is fetched periodically using GET.

  • Vicky can send a message, and Sanjana sees it instantly.

Example 3: Dynamic Content Loading

AJAX can be used to load content dynamically when a user clicks a button.

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:

  • When the button is clicked, AJAX fetches posts from the server.

  • Posts are displayed dynamically without page reload.

Benefits of AJAX Applications

  • Faster user experience: Only relevant data is loaded.

  • Interactive interface: Users like Sanjana can interact without refreshing.

  • Reduced server load: Only necessary requests are sent.

  • Real-time updates: Data can refresh automatically, e.g., chat or dashboards.

AJAX applications are widely used in social media, e-commerce, and content platforms.

Summary of the Tutorial

AJAX applications allow developers like Vicky to build responsive, interactive web applications where Sanjana can:

  • Search live results while typing.

  • Chat in real time.

  • Load content dynamically on demand.

By combining AJAX with server-side scripts and databases, web applications become faster, smoother, and user-friendly, making the overall experience enjoyable for users.


Practice Questions

  1. Create a live search input that fetches user data from search.php as the user types and displays results in a <div>.

  2. Build a chat interface where messages are sent via AJAX POST to send_message.php and fetched every 3 seconds from get_messages.php.

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

  4. Write an AJAX request to fetch JSON data from users.php and display only users older than 25.

  5. Create a form to submit feedback via AJAX POST to feedback.php and display a success message without reloading the page.

  6. Write code to fetch a list of products from products.php and dynamically display them in a table with name and price.

  7. Build a “Load More” button that fetches additional posts from the server using AJAX and appends them to the existing list.

  8. Create a search field that filters users by name and updates results live using AJAX and PHP.

  9. Write an AJAX POST request to vote on a poll and dynamically update the results bar chart without reloading.

  10. Create a function that automatically refreshes notifications every 5 seconds using AJAX GET and updates a <div> on the page.


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