AJAX Poll


Online polls are a common feature on websites to gather user opinions. Using AJAX allows the poll to submit votes and display results dynamically without refreshing the page. This improves user experience by making interactions instant and responsive.

In this tutorial, we will create a simple poll using AJAX, PHP, and MySQL, covering both vote submission and result display.

Setting Up the Database

We need a table to store poll options and votes:

CREATE DATABASE ajax_poll_demo;

USE ajax_poll_demo;

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

INSERT INTO poll (option_text, votes) VALUES
('Web Development', 0),
('Data Science', 0),
('UI/UX Design', 0),
('Digital Marketing', 0);

Each option starts with 0 votes and will be updated dynamically when users vote.

HTML Structure

index.html

<!DOCTYPE html>
<html>
<head>
  <title>AJAX Poll</title>
  <script>
    function vote(optionId) {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "vote.php", true);
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200){
          document.getElementById("result").innerHTML = xhr.responseText;
        }
      };
      xhr.send("id=" + optionId);
    }

    function loadResults() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "results.php", true);
      xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200){
          document.getElementById("result").innerHTML = xhr.responseText;
        }
      };
      xhr.send();
    }

    window.onload = function() {
      loadResults(); // Load current results on page load
    }
  </script>
</head>
<body>
  <h2>Vote for Your Favorite Course</h2>
  <button onclick="vote(1)">Web Development</button>
  <button onclick="vote(2)">Data Science</button>
  <button onclick="vote(3)">UI/UX Design</button>
  <button onclick="vote(4)">Digital Marketing</button>

  <h3>Results:</h3>
  <div id="result"></div>
</body>
</html>

Key Points

  • Each button calls the vote() function with the option ID.

  • loadResults() fetches and displays current results when the page loads.

  • XMLHttpRequest handles asynchronous communication with PHP.

PHP Script for Voting

vote.php

<?php
include "db.php"; // Database connection

if(isset($_POST['id'])){
    $id = intval($_POST['id']);

    // Increment vote count
    $sql = "UPDATE poll SET votes = votes + 1 WHERE id = $id";
    $conn->query($sql);
}

// Return updated results
$sql = "SELECT * FROM poll";
$result = $conn->query($sql);

if($result->num_rows > 0){
    echo "<ul style='list-style:none; padding:0;'>";
    while($row = $result->fetch_assoc()){
        echo "<li>".$row['option_text']." - ".$row['votes']." votes</li>";
    }
    echo "</ul>";
}

$conn->close();
?>

Explanation

  • Receives the selected id from AJAX POST.

  • Increments the vote count using UPDATE.

  • Returns updated results dynamically as an unordered list.

  • No page reload is required; results appear instantly.

PHP Script to Load Results

results.php

<?php
include "db.php";

$sql = "SELECT * FROM poll";
$result = $conn->query($sql);

if($result->num_rows > 0){
    echo "<ul style='list-style:none; padding:0;'>";
    while($row = $result->fetch_assoc()){
        echo "<li>".$row['option_text']." - ".$row['votes']." votes</li>";
    }
    echo "</ul>";
}

$conn->close();
?>

This ensures that the poll shows current results when the page loads or after voting.

Enhancing User Experience

  1. Prevent Multiple Votes: Use sessions or cookies to restrict users from voting multiple times.

  2. Progress Bars: Display results visually using progress bars instead of plain numbers.

  3. AJAX Refresh: Automatically refresh results every few seconds to show real-time votes.

  4. Styling Buttons and Results: Highlight the selected option and make results visually appealing.

Example: Simple CSS for progress bars:

<style>
  .bar {
    background-color: #4CAF50;
    height: 20px;
    color: white;
    text-align: center;
  }
</style>

Advantages of AJAX Poll

  1. Instant updates: Votes and results appear immediately without page reload.

  2. Better engagement: Users see their vote reflected dynamically.

  3. Efficient server communication: Only relevant data is sent and updated.

  4. Customizable and interactive: Can add animations, progress bars, or graphs.

  5. Scalable: Works for small websites and large-scale polls.

Security Tips

  • Sanitize user input to prevent SQL injection (use intval() or prepared statements).

  • Limit voting frequency using session tracking or IP checks.

  • Validate data server-side to prevent tampering with AJAX requests.

Summary of the Tutorial

Using AJAX for polls creates interactive and responsive voting features:

  • Users can submit votes and view results instantly.

  • PHP handles server-side updates and returns results dynamically.

  • MySQL stores poll data and ensures consistency.

  • Enhancements like progress bars, automatic refresh, and vote restriction improve usability.

AJAX polls are widely used in news sites, blogs, e-learning platforms, and product feedback forms to gather real-time user opinions while keeping the experience smooth and engaging.


Practice Questions

  1. Create a poll with four options that updates the vote count dynamically using AJAX.

  2. Modify the poll to display current results as progress bars instead of plain numbers.

  3. Implement a feature to prevent multiple votes from the same user using PHP sessions.

  4. Create a “Reset Poll” button that resets all votes to zero dynamically via AJAX.

  5. Add a real-time refresh that updates poll results every 5 seconds without refreshing the page.

  6. Display the percentage of votes for each option dynamically alongside the vote count.

  7. Allow users to vote using radio buttons and submit the selection via AJAX POST.

  8. Highlight the option a user voted for and keep it highlighted after the vote is submitted.

  9. Combine the poll with a small comment box that submits user comments via AJAX along with the vote.

  10. Create a PHP script that returns the top 3 most voted options dynamically and display them using AJAX.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top