AJAX Poll

Creating interactive voting polls with AJAX and PHP

📊 What is AJAX Poll?

AJAX Poll allows users to vote and see results instantly without page reload. It uses asynchronous requests to submit votes and update results dynamically for interactive user engagement.


// Submit vote via AJAX
function vote(option) {
    fetch('poll.php?vote=' + option)
        .then(response => response.text())
        .then(data => document.getElementById('results').innerHTML = data);
}
                                    

Demo:

What's your favorite color?

Poll System Components

🗳️

Voting Interface

Buttons or options for voting

<button 
  onclick="vote('option1')">
  Vote Option 1
</button>

AJAX Handler

Sends votes to server

function vote(choice) {
  fetch('poll.php?vote=' + choice)
    .then(r => r.text())
}
💾

Vote Storage

PHP saves votes to file/database

<?php
$vote = $_GET['vote'];
// Save to file
file_put_contents('votes.txt', $vote);
?>
📈

Results Display

Shows vote counts and percentages

<?php
echo "Option 1: 45%";
echo "Option 2: 55%";
?>

🔹 HTML Poll Form

Create a simple poll interface with voting options. Each button calls a JavaScript function to submit the vote via AJAX without refreshing the page.

<!DOCTYPE html>
<html>
<head>
    <title>AJAX Poll</title>
    <script src="poll.js"></script>
</head>
<body>
    <h2>What is your favorite programming language?</h2>
    
    <div id="pollOptions">
        <button onclick="vote('PHP')">PHP</button>
        <button onclick="vote('JavaScript')">JavaScript</button>
        <button onclick="vote('Python')">Python</button>
        <button onclick="vote('Java')">Java</button>
    </div>
    
    <div id="pollResults">
        <p>Click an option to vote</p>
    </div>
</body>
</html>

Output:

What is your favorite programming language?

Click an option to vote

🔹 JavaScript Vote Function

The JavaScript function sends the vote to the server and displays results. It hides voting buttons after voting and shows the updated poll results dynamically.

// poll.js
function vote(option) {
    // Hide voting buttons
    document.getElementById('pollOptions').style.display = 'none';
    
    // Show loading message
    document.getElementById('pollResults').innerHTML = 
        '<p>Submitting your vote...</p>';
    
    // Send vote to server
    fetch('poll.php?vote=' + encodeURIComponent(option))
        .then(response => response.text())
        .then(data => {
            // Display results
            document.getElementById('pollResults').innerHTML = data;
        })
        .catch(error => {
            document.getElementById('pollResults').innerHTML = 
                '<p>Error submitting vote. Please try again.</p>';
            document.getElementById('pollOptions').style.display = 'block';
        });
}

After voting:

Submitting your vote...

🔹 PHP Vote Handler

The PHP script receives votes, stores them in a file, and returns updated results. This example uses a simple text file to track votes for each option.

<?php
// poll.php
$vote = $_GET['vote'];
$votesFile = 'votes.txt';

// Initialize votes array
$votes = array(
    'PHP' => 0,
    'JavaScript' => 0,
    'Python' => 0,
    'Java' => 0
);

// Read existing votes
if(file_exists($votesFile)) {
    $data = file_get_contents($votesFile);
    $votes = json_decode($data, true);
}

// Add new vote
if(isset($votes[$vote])) {
    $votes[$vote]++;
}

// Save votes
file_put_contents($votesFile, json_encode($votes));

// Calculate total votes
$total = array_sum($votes);

// Display results
echo "<h3>Poll Results</h3>";
echo "<p>Total votes: $total</p>";

foreach($votes as $option => $count) {
    $percentage = $total > 0 ? round(($count / $total) * 100) : 0;
    echo "<div style='margin: 10px 0;'>";
    echo "<strong>$option:</strong> $count votes ($percentage%)<br>";
    echo "<div style='background: #e0e0e0; height: 20px; border-radius: 10px;'>";
    echo "<div style='background: #007cba; width: $percentage%; height: 100%; border-radius: 10px;'></div>";
    echo "</div></div>";
}
?>

Sample Output:

Poll Results

Total votes: 100

PHP: 35 votes (35%)
JavaScript: 40 votes (40%)

🔹 Database Poll System

For production applications, store votes in a database for better reliability and scalability. This example uses MySQL to track votes with timestamps.

<?php
// poll_db.php
$vote = $_GET['vote'];

// Database connection
$conn = mysqli_connect("localhost", "username", "password", "database");

// Insert vote
$stmt = $conn->prepare("INSERT INTO poll_votes (option_name, vote_time) VALUES (?, NOW())");
$stmt->bind_param("s", $vote);
$stmt->execute();

// Get vote counts
$result = $conn->query("SELECT option_name, COUNT(*) as count FROM poll_votes GROUP BY option_name");

$votes = array();
$total = 0;
while($row = $result->fetch_assoc()) {
    $votes[$row['option_name']] = $row['count'];
    $total += $row['count'];
}

// Display results
echo "<h3>Poll Results</h3>";
echo "<p>Total votes: $total</p>";

foreach($votes as $option => $count) {
    $percentage = round(($count / $total) * 100);
    echo "<div style='margin: 10px 0;'>";
    echo "<strong>" . htmlspecialchars($option) . ":</strong> $count votes ($percentage%)<br>";
    echo "<div style='background: #e0e0e0; height: 20px; border-radius: 10px;'>";
    echo "<div style='background: #007cba; width: $percentage%; height: 100%; border-radius: 10px;'></div>";
    echo "</div></div>";
}

$conn->close();
?>

Database Table:

CREATE TABLE poll_votes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  option_name VARCHAR(100),
  vote_time DATETIME
);

🔹 Prevent Multiple Votes

Use cookies or IP tracking to prevent users from voting multiple times. This example uses a cookie to track if a user has already voted.

<?php
// poll_cookie.php
$vote = $_GET['vote'];

// Check if user already voted
if(isset($_COOKIE['poll_voted'])) {
    echo "<p style='color: red;'>You have already voted!</p>";
    // Show results without accepting vote
    include 'show_results.php';
    exit;
}

// Process vote
$votesFile = 'votes.txt';
$votes = json_decode(file_get_contents($votesFile), true);
$votes[$vote]++;
file_put_contents($votesFile, json_encode($votes));

// Set cookie (expires in 30 days)
setcookie('poll_voted', '1', time() + (30 * 24 * 60 * 60), '/');

// Show results
$total = array_sum($votes);
echo "<h3>Thank you for voting!</h3>";
echo "<p>Total votes: $total</p>";

foreach($votes as $option => $count) {
    $percentage = round(($count / $total) * 100);
    echo "<div><strong>$option:</strong> $count votes ($percentage%)</div>";
}
?>

After voting:

Thank you for voting!

Total votes: 150

🧠 Test Your Knowledge

What is the best way to prevent multiple votes in a poll?