PHP Example – AJAX Poll

Welcome to The Coding College! In this tutorial, we will implement an AJAX-powered Poll System using PHP and MySQL. A poll allows users to vote on a specific question and instantly see the results without reloading the webpage.

What is an AJAX Poll?

  • AJAX dynamically sends data to the server without reloading the webpage.
  • PHP processes user input and updates the database.
  • MySQL stores the poll options and vote counts.
  • The results update in real-time, providing a smooth user experience.

Example Overview

We will:

  1. Create a MySQL database to store poll data.
  2. Develop a PHP script to handle votes and display results.
  3. Use AJAX to send user votes to the server.
  4. Display updated poll results dynamically.

Step 1: Set Up the MySQL Database

Create a table to store poll options and vote counts.

SQL Script to Create the Database Table

CREATE DATABASE ajax_poll_demo;

USE ajax_poll_demo;

CREATE TABLE poll_options (
    id INT AUTO_INCREMENT PRIMARY KEY,
    option_name VARCHAR(100) NOT NULL,
    vote_count INT DEFAULT 0
);

INSERT INTO poll_options (option_name) VALUES ('Option A'), ('Option B'), ('Option C'), ('Option D');

Step 2: Create the Poll HTML Page

This HTML page displays the poll options, and users can submit their votes using radio buttons.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Poll Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        .poll-container {
            margin: 20px;
        }
        .poll-results {
            margin-top: 20px;
        }
        button {
            padding: 8px 12px;
            margin-top: 10px;
        }
    </style>
    <script>
        function submitVote() {
            const options = document.getElementsByName("poll");
            let selectedOption = "";

            for (let i = 0; i < options.length; i++) {
                if (options[i].checked) {
                    selectedOption = options[i].value;
                    break;
                }
            }

            if (selectedOption === "") {
                alert("Please select an option!");
                return;
            }

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

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

            xhr.send("vote=" + selectedOption);
        }

        function loadResults() {
            const xhr = new XMLHttpRequest();
            xhr.open("GET", "poll.php", true);

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

            xhr.send();
        }

        window.onload = loadResults; // Load poll results on page load
    </script>
</head>
<body>
    <h1>AJAX Poll Example</h1>
    <div class="poll-container">
        <p><strong>Which option do you prefer?</strong></p>
        <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>
        <label><input type="radio" name="poll" value="4"> Option D</label><br>
        <button onclick="submitVote()">Vote</button>
    </div>
    <div id="poll-results" class="poll-results">
        <!-- Poll results will load here dynamically -->
    </div>
</body>
</html>

Explanation

  1. Radio Buttons: Each poll option has a radio button with a unique value corresponding to the option ID.
  2. AJAX Request:
    • submitVote(): Sends the selected vote to the server.
    • loadResults(): Fetches the current poll results on page load.
  3. Results Div: Poll results dynamically update without refreshing the page.

Step 3: Create the PHP Script

Create a file poll.php to process votes and return poll results.

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

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

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

// Handle vote submission
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['vote'])) {
    $vote = intval($_POST['vote']);

    // Update the vote count
    $sql = "UPDATE poll_options SET vote_count = vote_count + 1 WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $vote);
    $stmt->execute();
    $stmt->close();
}

// Fetch and display current poll results
$sql = "SELECT option_name, vote_count FROM poll_options";
$result = $conn->query($sql);

echo "<h3>Poll Results:</h3>";
$totalVotes = 0;
while ($row = $result->fetch_assoc()) {
    $totalVotes += $row['vote_count'];
}

$result->data_seek(0); // Reset result pointer

if ($totalVotes > 0) {
    while ($row = $result->fetch_assoc()) {
        $percentage = round(($row['vote_count'] / $totalVotes) * 100, 2);
        echo "<p>{$row['option_name']}: {$row['vote_count']} votes ({$percentage}%)</p>";
    }
} else {
    echo "<p>No votes yet. Be the first to vote!</p>";
}

$conn->close();
?>

Explanation

  1. Database Connection: Connects to the MySQL database.
  2. Vote Submission:
    • Checks for a POST request.
    • Updates the vote count in the poll_options table.
  3. Fetch Results: Retrieves the current vote count for all options.
  4. Dynamic Results: Calculates and displays the percentage of votes for each option.

How It Works

  1. Users select an option and click the “Vote” button.
  2. An AJAX POST request is sent to poll.php with the selected vote.
  3. The PHP script updates the database and returns the updated poll results.
  4. The poll-results div dynamically displays the updated results.
  5. Results are loaded on page load using loadResults().

Output

Initial Poll Display:

Which option do you prefer?
- Option A
- Option B
- Option C
- Option D

After Voting:

Poll Results:
Option A: 5 votes (50%)
Option B: 3 votes (30%)
Option C: 2 votes (20%)
Option D: 0 votes (0%)

Benefits of AJAX Poll

  1. Real-time Updates: Results display instantly without page reloads.
  2. Improved User Experience: Smooth and interactive voting process.
  3. Efficient Data Handling: Only relevant data is sent to the server.

Conclusion

In this tutorial, we implemented an AJAX-based Poll System using PHP and MySQL. Users can vote dynamically, and results are updated in real time.

Next Steps:

  • Add error handling to prevent duplicate votes using user sessions or IP tracking.
  • Customize the poll to support images or more complex layouts.

Leave a Comment