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


JavaScript AJAX examples help you understand how asynchronous communication actually works in real applications. While learning theory is important, AJAX becomes much clearer when you see how it is used to solve practical problems like loading data, submitting forms, searching records, and updating content dynamically. AJAX allows web pages to communicate with the server in the background and update specific parts of the page without reloading.

In this tutorial, you will explore multiple JavaScript AJAX examples, starting from simple requests to more practical, real-world use cases. Each example focuses on a common scenario you will face while building modern web applications.

Basic AJAX Request Example

This is the simplest form of an AJAX request using XMLHttpRequest. It demonstrates how data is fetched from the server and displayed on the page.

Example: Load Text File Content

JavaScript code:

function loadContent() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "data.txt", true);

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

    xhr.send();
}

HTML:

<button onclick="loadContent()">Load Data</button>
<div id="output"></div>

This example loads data from a text file and displays it instantly without refreshing the page.

AJAX Example with HTML Response

AJAX can load HTML fragments dynamically, which is useful for dashboards and content sections.

Example: Load HTML Content

function loadProfile() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "profile.html", true);

    xhr.onload = function () {
        document.getElementById("profileSection").innerHTML = xhr.responseText;
    };

    xhr.send();
}

This approach is commonly used in admin panels where sections are loaded on demand.

AJAX Example with PHP and Database

One of the most common AJAX examples involves fetching data from a database using PHP.

Example: Fetch User List

JavaScript:

function loadUsers() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "users.php", true);

    xhr.onload = function () {
        document.getElementById("userList").innerHTML = xhr.responseText;
    };

    xhr.send();
}

PHP:

<?php
$conn = mysqli_connect("localhost", "root", "", "demo");
$result = mysqli_query($conn, "SELECT name FROM users");

while ($row = mysqli_fetch_assoc($result)) {
    echo "<p>" . $row['name'] . "</p>";
}
?>

This example dynamically loads database records into the page.

AJAX Form Submission Example

Submitting forms using AJAX improves user experience by avoiding page reloads.

Example: Contact Form Submission

JavaScript:

function submitForm() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "submit.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onload = function () {
        document.getElementById("message").innerHTML = xhr.responseText;
    };

    xhr.send("name=Ananya&email=ananya@gmail.com");
}

PHP:

<?php
echo "Form submitted successfully";
?>

This pattern is widely used in feedback and inquiry forms.

AJAX Live Search Example

Live search updates results as the user types.

Example: Search Records Instantly

JavaScript:

function searchData(value) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "search.php?q=" + value, true);

    xhr.onload = function () {
        document.getElementById("results").innerHTML = xhr.responseText;
    };

    xhr.send();
}

HTML:

<input type="text" onkeyup="searchData(this.value)">
<div id="results"></div>

This technique is used in product search, student lookup, and autocomplete features.

AJAX Pagination Example

Pagination with AJAX loads records page by page.

Example: Load Paginated Data

JavaScript:

function loadPage(page) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "records.php?page=" + page, true);

    xhr.onload = function () {
        document.getElementById("records").innerHTML = xhr.responseText;
    };

    xhr.send();
}

This improves performance by loading only required data.

AJAX JSON Example

JSON is the most commonly used data format in AJAX applications.

Example: Fetch JSON Data

PHP:

<?php
$data = [
    ["name" => "Ravi", "age" => 22],
    ["name" => "Kavita", "age" => 24]
];
echo json_encode($data);
?>

JavaScript:

var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);

xhr.onload = function () {
    var users = JSON.parse(xhr.responseText);
    users.forEach(function(user) {
        console.log(user.name + " - " + user.age);
    });
};

xhr.send();

JSON makes data handling clean and efficient.

AJAX Loader Example

Showing a loader improves user experience.

xhr.onloadstart = function () {
    document.getElementById("loader").style.display = "block";
};

xhr.onloadend = function () {
    document.getElementById("loader").style.display = "none";
};

Loaders indicate that a request is being processed.

AJAX Error Handling Example

Handling errors ensures stability.

xhr.onerror = function () {
    console.log("Request failed");
};

Always include error handling in production applications.

AJAX Real-World Example: Online Quiz

AJAX is widely used in online tests.

Features:

  • Load questions dynamically

  • Submit answers without reload

  • Save progress automatically

This approach improves reliability and performance.

Performance Tips for AJAX Examples

  • Reduce request frequency

  • Cache responses when possible

  • Use JSON instead of HTML

  • Optimize backend queries

  • Avoid sending unnecessary data

Efficient AJAX usage ensures smooth applications.

Common Mistakes in AJAX Examples

  • Forgetting asynchronous behavior

  • Not validating server responses

  • Using GET for sensitive data

  • Ignoring network failures

  • Mixing frontend and backend logic

Understanding these mistakes helps avoid bugs.

Best Practices

  • Keep AJAX code modular

  • Use clear request URLs

  • Handle success and error states

  • Provide user feedback

  • Test under slow network conditions

These practices help in building scalable applications.

Real-World Use Cases

JavaScript AJAX examples appear in:

  • Login systems

  • Live notifications

  • Shopping cart updates

  • Admin dashboards

  • Student management systems

AJAX is essential for interactive websites.

Summary of JavaScript Ajax Examples

JavaScript AJAX examples demonstrate how asynchronous requests transform traditional websites into dynamic applications. By loading data, submitting forms, searching records, and updating content without page reloads, AJAX improves performance and user experience. Understanding these examples prepares you to build real-world applications that are fast, responsive, and scalable. Practicing different AJAX scenarios helps you master both frontend and backend communication effectively.


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>.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

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