How to Create a Real-Time PHP AJAX Poll System (With Live Vote Updates)

Last updated 2 months, 3 weeks ago | 155 views 75     5

Tags:- PHP

Introduction: Why Use PHP AJAX for Polls?

Online polls are a great way to collect user opinions and engage visitors—but no one wants to reload the page just to vote or see results.

That’s where PHP AJAX polls come in. Using AJAX, you can allow users to submit votes and instantly see updated results, all without refreshing the page. Combined with PHP and MySQL, this gives you a smooth, interactive polling system perfect for blogs, news sites, product feedback, and more.


What You’ll Build

In this tutorial, you’ll create a simple yet functional AJAX-based poll system with the following features:

  • A form with multiple poll options

  • A backend PHP script to handle vote storage

  • Real-time result updates after voting

  • MySQL database to track poll data


Step-by-Step Guide: PHP AJAX Poll System

✅ Step 1: Set Up the Database

CREATE DATABASE poll_db;

USE poll_db;

CREATE TABLE poll (
    id INT AUTO_INCREMENT PRIMARY KEY,
    option_text VARCHAR(100) NOT NULL,
    votes INT DEFAULT 0
);

INSERT INTO poll (option_text) VALUES
('Option A'),
('Option B'),
('Option C');

✅ Step 2: Create the HTML Form and JavaScript

index.html

<!DOCTYPE html>
<html>
<head>
    <title>PHP AJAX Poll</title>
    <script>
    function submitVote() {
        const selected = document.querySelector('input[name="poll"]:checked');
        if (!selected) {
            alert("Please select an option.");
            return;
        }

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

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

        xhr.send("option_id=" + selected.value);
    }
    </script>
</head>
<body>
    <h2>What's your favorite option?</h2>
    <form id="poll-form" onsubmit="event.preventDefault(); submitVote();">
        <label><input type="radio" name="poll" value="1"> Option A</label><br>
        <label><input type="radio" name="poll" value="2"> Option B</label><br>
        <label><input type="radio" name="poll" value="3"> Option C</label><br><br>
        <button type="submit">Vote</button>
    </form>

    <div id="poll-results" style="margin-top: 20px;"></div>
</body>
</html>

✅ Step 3: Handle Vote Submission in PHP

vote.php

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "poll_db";

// Create DB connection
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get submitted option ID
$optionId = isset($_POST['option_id']) ? (int) $_POST['option_id'] : 0;

if ($optionId > 0) {
    // Update vote count
    $stmt = $conn->prepare("UPDATE poll SET votes = votes + 1 WHERE id = ?");
    $stmt->bind_param("i", $optionId);
    $stmt->execute();
    $stmt->close();
}

// Fetch updated results
$sql = "SELECT option_text, votes FROM poll";
$result = $conn->query($sql);

$totalVotes = 0;
$pollData = [];

while ($row = $result->fetch_assoc()) {
    $totalVotes += $row['votes'];
    $pollData[] = $row;
}

// Display results
foreach ($pollData as $row) {
    $percent = $totalVotes > 0 ? round(($row['votes'] / $totalVotes) * 100) : 0;
    echo "<p><strong>{$row['option_text']}:</strong> {$percent}% ({$row['votes']} votes)</p>";
}

$conn->close();
?>

Full Working Example Structure

ajax-poll/
├── index.html
└── vote.php

✅ How It Works:

  1. The user selects an option and clicks Vote.

  2. AJAX sends the vote to vote.php.

  3. PHP updates the database and returns updated poll results.

  4. JavaScript displays the new results instantly.


Tips & Common Pitfalls

✅ Best Practices

  • Use prepared statements to avoid SQL injection.

  • Sanitize input using (int) or filter_input() for better security.

  • Disable multiple votes from the same user (using sessions or IP logging).

  • Use a loading indicator for smoother UX.

❌ Common Mistakes

Issue Fix
Votes not updating Ensure the database connection is working and the correct option_id is sent
Results not displaying Check the xhr.responseText and debug using browser dev tools
Duplicate votes Implement session/IP control logic

Optional: Improve UX with a Progress Bar

// Replace echo line with this
echo "<div style='margin-bottom: 8px;'>
        <strong>{$row['option_text']}:</strong> {$percent}% 
        <div style='width: 100%; background: #eee;'>
            <div style='width: {$percent}%; background: #4caf50; color: white; padding: 2px;'>{$row['votes']} votes</div>
        </div>
      </div>";

This adds a visual bar to the poll results.


✅ Conclusion: Bring Your Polls to Life with PHP AJAX

A PHP AJAX poll system brings your web application to life—making it interactive, fast, and user-friendly. With just a few lines of code, you can create a real-time voting feature that engages your users without disrupting their experience.


Key Takeaways:

  • AJAX + PHP + MySQL = powerful real-time functionality

  • Use AJAX to submit votes and retrieve updated results asynchronously

  • Sanitize inputs and secure your backend with prepared statements

  • Enhance UX with live updates, progress bars, and response handling