PHP AJAX

This article explains AJAX with PHP in detail, including AJAX intro, sending requests to PHP, working with databases, loading XML data, building live search, and creating a simple AJAX poll system.

Jun 10, 2026
PHP AJAX

PHP AJAX: Intro, PHP Requests, Database, XML, Live Search and Poll

AJAX is an important technique in web development because it allows a web page to communicate with the server without reloading the entire page. This makes websites feel faster, smoother, and more interactive.

PHP can be used on the server side to receive AJAX requests, process data, read or write to a database, return JSON or XML responses, and update parts of a web page dynamically.

This article explains the main PHP AJAX topics shown in the learning path: AJAX intro, AJAX PHP, AJAX database, AJAX XML, AJAX live search, and AJAX poll.

AJAX Intro

AJAX stands for Asynchronous JavaScript and XML. The name includes XML because XML was commonly used in older AJAX applications. Today, JSON is more common, but the name AJAX is still used.

The main idea of AJAX is simple: JavaScript sends a request to the server in the background, the server processes the request, and JavaScript updates part of the page using the response.

Without AJAX, a user action often requires a full page reload. With AJAX, only the necessary data is loaded or updated.

A basic AJAX workflow looks like this:

  1. The user performs an action, such as typing in a search box or clicking a button.

  2. JavaScript sends a request to a PHP file.

  3. PHP receives the request and processes it.

  4. PHP returns a response, such as text, JSON, HTML, or XML.

  5. JavaScript receives the response and updates the page without refreshing it.

AJAX is commonly used for live search, form submission, comments, notifications, voting systems, dashboards, filtering, pagination, and loading more content.

Why AJAX Is Useful

AJAX improves user experience because it reduces unnecessary page reloads. It allows the website to feel more like an application instead of a collection of static pages.

For example, a search box can show results while the user types. A form can submit data and show a success message without leaving the page. A dashboard can refresh statistics in the background.

AJAX is useful because it can:

  • Update part of a page without reloading the whole page.

  • Send data to the server in the background.

  • Load data only when needed.

  • Improve speed and interactivity.

  • Make forms and search features smoother.

  • Reduce unnecessary server-rendered page reloads.

In modern web development, AJAX is often implemented using the fetch() API or libraries such as Axios. Older examples may use XMLHttpRequest.

AJAX PHP

PHP can receive AJAX requests just like normal form requests. The difference is that the request is sent by JavaScript in the background instead of the browser loading a new page.

The following example shows a simple HTML button that sends an AJAX request to a PHP file using fetch.

<button id="loadMessage">Load Message</button>
<div id="result"></div>

<script>
document.getElementById("loadMessage").addEventListener("click", function () {
    fetch("message.php")
        .then(function (response) {
            return response.text();
        })
        .then(function (data) {
            document.getElementById("result").innerHTML = data;
        });
});
</script>

The PHP file can return a simple response.

<?php
echo "Hello from PHP AJAX!";
?>

When the user clicks the button, JavaScript sends a request to message.php. PHP returns the message, and JavaScript displays it inside the page.

AJAX can also send data to PHP using query parameters or POST requests.

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

<script>
document.getElementById("sendName").addEventListener("click", function () {
    const name = document.getElementById("name").value;

    fetch("greet.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: "name=" + encodeURIComponent(name)
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById("response").innerHTML = data;
    });
});
</script>

The PHP file can read the submitted value using $_POST.

<?php
$name = trim($_POST["name"] ?? "");

if ($name === "") {
    echo "Please enter your name.";
} else {
    echo "Hello, " . htmlspecialchars($name, ENT_QUOTES, "UTF-8");
}
?>

This example shows how AJAX and PHP work together. JavaScript sends the request, PHP processes the data, and JavaScript displays the result.

Returning JSON from PHP

Although AJAX originally used XML, modern applications often return JSON because it is easier to work with in JavaScript.

PHP can return JSON using json_encode() and the correct content type header.

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

$response = [
    "success" => true,
    "message" => "Data loaded successfully.",
    "items" => ["PHP", "AJAX", "MySQL"]
];

echo json_encode($response);
?>

JavaScript can read the JSON response using response.json().

<script>
fetch("data.php")
    .then(response => response.json())
    .then(data => {
        console.log(data.message);
        console.log(data.items);
    });
</script>

JSON responses are commonly used in APIs, dashboards, dynamic forms, search suggestions, and single-page interactions.

AJAX Database

AJAX can be used with PHP and MySQL to load or save database data without refreshing the page. This is useful for live search, filtering, comments, notifications, likes, votes, and admin panels.

For example, JavaScript can send a search keyword to PHP, and PHP can query the database and return matching results.

The following example sends a keyword to a PHP file.

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

<script>
document.getElementById("search").addEventListener("input", function () {
    const keyword = this.value;

    fetch("search-users.php?q=" + encodeURIComponent(keyword))
        .then(response => response.json())
        .then(users => {
            let html = "";

            users.forEach(function (user) {
                html += "<p>" + user.name + " - " + user.email + "</p>";
            });

            document.getElementById("results").innerHTML = html;
        });
});
</script>

The PHP file can receive the keyword, query the database using a prepared statement, and return JSON.

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

$pdo = new PDO(
    "mysql:host=localhost;dbname=php_learning;charset=utf8mb4",
    "root",
    ""
);

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q = trim($_GET["q"] ?? "");

$statement = $pdo->prepare("
    SELECT id, name, email
    FROM users
    WHERE name LIKE :keyword OR email LIKE :keyword
    ORDER BY name ASC
    LIMIT 10
");

$statement->execute([
    "keyword" => "%" . $q . "%"
]);

$users = $statement->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($users);
?>

This example demonstrates how AJAX, PHP, and MySQL can work together. The user types a keyword, JavaScript sends it to PHP, PHP searches the database, and the page displays the results instantly.

Prepared statements are important here because the search keyword comes from user input. Directly placing user input into SQL can create SQL injection risks.

AJAX XML

AJAX can also load XML data. Although JSON is more common today, XML is still used in sitemaps, RSS feeds, SOAP services, legacy systems, and some external integrations.

An XML file may look like this:

<articles>
    <article>
        <title>PHP AJAX Intro</title>
        <category>PHP</category>
    </article>
    <article>
        <title>AJAX Database</title>
        <category>MySQL</category>
    </article>
</articles>

JavaScript can load this XML file using fetch and parse it using DOMParser.

<div id="xmlResults"></div>

<script>
fetch("articles.xml")
    .then(response => response.text())
    .then(xmlText => {
        const parser = new DOMParser();
        const xml = parser.parseFromString(xmlText, "application/xml");

        const articles = xml.getElementsByTagName("article");
        let html = "";

        for (let i = 0; i < articles.length; i++) {
            const title = articles[i].getElementsByTagName("title")[0].textContent;
            const category = articles[i].getElementsByTagName("category")[0].textContent;

            html += "<p>" + title + " - " + category + "</p>";
        }

        document.getElementById("xmlResults").innerHTML = html;
    });
</script>

PHP can also generate XML dynamically and return it to AJAX.

<?php
header("Content-Type: application/xml; charset=UTF-8");

echo '<articles>';
echo '<article>';
echo '<title>PHP AJAX XML</title>';
echo '<category>PHP</category>';
echo '</article>';
echo '</articles>';
?>

AJAX XML is useful when integrating with systems that still use XML or when reading XML documents such as feeds and sitemaps.

AJAX Live Search

Live search is one of the most common AJAX examples. It allows users to see search results while typing, without pressing a submit button or reloading the page.

A live search feature usually works like this:

  1. The user types in a search input.

  2. JavaScript listens to the input event.

  3. AJAX sends the current keyword to PHP.

  4. PHP searches data from an array, file, API, or database.

  5. PHP returns matching results.

  6. JavaScript displays the results under the input.

The following example uses a PHP array for simplicity.

<input type="text" id="liveSearch" placeholder="Search topics">
<div id="liveResults"></div>

<script>
document.getElementById("liveSearch").addEventListener("input", function () {
    const keyword = this.value;

    if (keyword.length === 0) {
        document.getElementById("liveResults").innerHTML = "";
        return;
    }

    fetch("live-search.php?q=" + encodeURIComponent(keyword))
        .then(response => response.text())
        .then(data => {
            document.getElementById("liveResults").innerHTML = data;
        });
});
</script>

The PHP file can search inside a simple array and return HTML.

<?php
$topics = [
    "PHP Basics",
    "PHP Forms",
    "PHP OOP",
    "PHP MySQL",
    "PHP AJAX",
    "Laravel Framework",
    "JavaScript Fetch API"
];

$q = strtolower(trim($_GET["q"] ?? ""));
$results = [];

if ($q !== "") {
    foreach ($topics as $topic) {
        if (str_contains(strtolower($topic), $q)) {
            $results[] = $topic;
        }
    }
}

if (count($results) === 0) {
    echo "<p>No results found.</p>";
} else {
    foreach ($results as $result) {
        echo "<p>" . htmlspecialchars($result, ENT_QUOTES, "UTF-8") . "</p>";
    }
}
?>

For better performance in real applications, live search should avoid sending too many requests. Developers often use debounce, which waits for a short delay after the user stops typing before sending the request.

<script>
let timer;

document.getElementById("liveSearch").addEventListener("input", function () {
    clearTimeout(timer);

    const keyword = this.value;

    timer = setTimeout(function () {
        fetch("live-search.php?q=" + encodeURIComponent(keyword))
            .then(response => response.text())
            .then(data => {
                document.getElementById("liveResults").innerHTML = data;
            });
    }, 300);
});
</script>

Debounce helps reduce server load and makes the feature more efficient.

AJAX Poll

An AJAX poll system allows users to vote and see updated results without refreshing the page. This is useful for surveys, voting widgets, feedback systems, and simple interactive content.

A poll usually includes a question, multiple options, a vote button, and a result area.

<h3>Which language do you like most?</h3>

<label>
    <input type="radio" name="vote" value="PHP"> PHP
</label>

<label>
    <input type="radio" name="vote" value="JavaScript"> JavaScript
</label>

<label>
    <input type="radio" name="vote" value="Python"> Python
</label>

<button id="voteButton">Vote</button>

<div id="pollResults"></div>

<script>
document.getElementById("voteButton").addEventListener("click", function () {
    const selected = document.querySelector("input[name='vote']:checked");

    if (!selected) {
        document.getElementById("pollResults").innerHTML = "Please select an option.";
        return;
    }

    fetch("poll.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: "vote=" + encodeURIComponent(selected.value)
    })
    .then(response => response.text())
    .then(data => {
        document.getElementById("pollResults").innerHTML = data;
    });
});
</script>

The PHP file can receive the selected vote and update the result. For a simple example, the votes can be stored in a JSON file.

<?php
$allowedVotes = ["PHP", "JavaScript", "Python"];
$vote = $_POST["vote"] ?? "";

if (!in_array($vote, $allowedVotes)) {
    echo "Invalid vote.";
    exit;
}

$file = "poll-results.json";

if (!file_exists($file)) {
    file_put_contents($file, json_encode([
        "PHP" => 0,
        "JavaScript" => 0,
        "Python" => 0
    ]));
}

$results = json_decode(file_get_contents($file), true);

$results[$vote]++;

file_put_contents($file, json_encode($results));

foreach ($results as $option => $count) {
    echo "<p>" . htmlspecialchars($option, ENT_QUOTES, "UTF-8") . ": " . $count . " votes</p>";
}
?>

This example demonstrates the basic AJAX poll idea. In a real project, poll results are usually stored in a database, and the system may prevent repeated voting using sessions, login accounts, cookies, or IP-based limits.

AJAX Error Handling

AJAX requests can fail for many reasons. The PHP file may return an error, the network may fail, the server may be unavailable, or the response may not be in the expected format.

JavaScript should handle errors instead of assuming every request will succeed.

<script>
fetch("data.php")
    .then(response => {
        if (!response.ok) {
            throw new Error("Request failed.");
        }

        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.error(error);
    });
</script>

PHP can also return clear JSON responses that indicate success or failure.

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

try {
    echo json_encode([
        "success" => true,
        "message" => "Request completed successfully."
    ]);
} catch (Exception $exception) {
    echo json_encode([
        "success" => false,
        "message" => "Something went wrong."
    ]);
}
?>

Good error handling makes AJAX features more reliable and easier to debug.

Security Notes for AJAX with PHP

AJAX requests are still normal HTTP requests. This means they must be validated and protected just like normal form submissions.

Important security practices include:

  • Validate all data received through AJAX.

  • Use prepared statements for database queries.

  • Escape output before displaying user-generated data.

  • Use CSRF protection for sensitive actions.

  • Do not trust hidden fields or JavaScript-only validation.

  • Check user permissions before updating or deleting data.

  • Return safe error messages without exposing server details.

  • Limit request frequency for live search and poll systems.

AJAX improves user experience, but it does not replace backend validation and security. The server must always make the final decision.

How AJAX and PHP Work Together in Real Projects

In real PHP applications, AJAX is used to make pages more interactive. A dashboard may use AJAX to refresh statistics. A blog may use AJAX to load more posts. An admin panel may use AJAX to update status values. A profile page may use AJAX to upload or validate data.

Common real-world AJAX use cases include:

  • Live search suggestions.

  • Contact form submission without page reload.

  • Loading more posts or products.

  • Filtering tables and lists.

  • Updating notification counters.

  • Voting and poll systems.

  • Checking username or email availability.

  • Saving user preferences.

When PHP returns clean JSON responses and JavaScript handles them properly, AJAX becomes a powerful way to build smooth and modern web interfaces.

Conclusion

AJAX with PHP allows web pages to communicate with the server in the background without refreshing the whole page. This makes websites more dynamic, responsive, and user-friendly.

The main PHP AJAX topics include AJAX intro, sending requests to PHP, working with databases, loading XML data, building live search, and creating poll systems.

After understanding these concepts, the next step is to practice by building small AJAX projects such as a live search box, contact form, database filter, voting system, and JSON API response. These projects will help connect PHP backend logic with interactive frontend behavior.