Implementing a jQuery-based poll or voting system

Loading

Implementing a jQuery-Based Poll or Voting System

Creating a poll or voting system using jQuery can be an effective way to engage users on your website while collecting their opinions. In this guide, we will go through every step involved in building a dynamic poll system using jQuery, HTML, CSS, and PHP (for backend processing). This tutorial assumes basic knowledge of jQuery, JavaScript, AJAX, and PHP.


Table of Contents

  1. Introduction to Poll Systems
  2. Setting Up the Project
  3. Creating the Poll HTML Structure
  4. Styling the Poll with CSS
  5. Handling User Interaction with jQuery
  6. Sending Votes to the Server Using AJAX
  7. Processing Votes with PHP and MySQL
  8. Storing and Retrieving Poll Data from Database
  9. Displaying Poll Results Dynamically
  10. Preventing Multiple Votes
  11. Enhancing User Experience
  12. Testing and Debugging
  13. Security Considerations
  14. Conclusion

1. Introduction to Poll Systems

A poll system allows users to vote on a given question and see the results instantly. The key features of a poll system include:

  • Displaying a question with multiple answer choices
  • Allowing users to select one option and submit their vote
  • Sending the vote to the server
  • Storing the vote in a database
  • Displaying real-time results
  • Preventing duplicate voting

Technologies Used:

  • Frontend: HTML, CSS, jQuery
  • Backend: PHP, MySQL
  • Communication: AJAX

2. Setting Up the Project

To begin, create a project folder structure like this:

poll-system/
│── index.html        # Main UI for the poll
│── style.css         # CSS file for styling
│── script.js         # jQuery script
│── process.php       # Handles AJAX requests
│── database.sql      # SQL script for database setup

3. Creating the Poll HTML Structure

The poll interface consists of a question and multiple options.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Poll System with jQuery</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="poll-container">
        <h2>Which programming language do you prefer?</h2>
        <form id="pollForm">
            <label>
                <input type="radio" name="poll_option" value="JavaScript"> JavaScript
            </label><br>
            <label>
                <input type="radio" name="poll_option" value="Python"> Python
            </label><br>
            <label>
                <input type="radio" name="poll_option" value="Java"> Java
            </label><br>
            <label>
                <input type="radio" name="poll_option" value="C#"> C#
            </label><br>
            <button type="submit">Vote</button>
        </form>
        <div id="pollResults"></div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

4. Styling the Poll with CSS

Now, let’s add some basic styles.

style.css

body {
    font-family: Arial, sans-serif;
    background: #f4f4f4;
    text-align: center;
    margin-top: 50px;
}

.poll-container {
    width: 50%;
    background: white;
    padding: 20px;
    margin: auto;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}

button {
    margin-top: 10px;
    padding: 10px;
    background: blue;
    color: white;
    border: none;
    cursor: pointer;
}

#pollResults {
    margin-top: 20px;
    font-weight: bold;
}

5. Handling User Interaction with jQuery

The next step is writing jQuery code to capture user votes.

script.js

$(document).ready(function() {
    $("#pollForm").submit(function(event) {
        event.preventDefault(); // Prevent form submission

        var selectedOption = $("input[name='poll_option']:checked").val();
        if (!selectedOption) {
            alert("Please select an option before voting.");
            return;
        }

        $.ajax({
            url: "process.php",
            type: "POST",
            data: { vote: selectedOption },
            success: function(response) {
                $("#pollResults").html(response);
            }
        });
    });
});

6. Sending Votes to the Server Using AJAX

The above script sends the selected option to process.php using AJAX.


7. Processing Votes with PHP and MySQL

Create a database and table to store poll results.

database.sql

CREATE DATABASE pollDB;
USE pollDB;

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

Pre-fill options:

INSERT INTO poll_results (option_text, votes) VALUES 
('JavaScript', 0), 
('Python', 0), 
('Java', 0), 
('C#', 0);

8. Storing and Retrieving Poll Data from Database

Now, write the process.php script.

process.php

<?php
$conn = new mysqli("localhost", "root", "", "pollDB");

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $vote = $_POST['vote'];

    $stmt = $conn->prepare("UPDATE poll_results SET votes = votes + 1 WHERE option_text = ?");
    $stmt->bind_param("s", $vote);
    $stmt->execute();
    $stmt->close();
}

// Retrieve updated results
$result = $conn->query("SELECT option_text, votes FROM poll_results");

$output = "<h3>Poll Results:</h3>";
while ($row = $result->fetch_assoc()) {
    $output .= "<p>" . $row['option_text'] . ": " . $row['votes'] . " votes</p>";
}

echo $output;
$conn->close();
?>

9. Displaying Poll Results Dynamically

Whenever a user votes, the results update dynamically using jQuery.


10. Preventing Multiple Votes

To prevent multiple votes:

  1. Use Cookies or Local Storage to track votes.
  2. Store user IP address in the database and prevent duplicate votes.

11. Enhancing User Experience

  • Add animations when submitting votes.
  • Display a loading indicator while AJAX request is in progress.

12. Testing and Debugging

  • Check the console for AJAX request errors.
  • Test on different browsers.

13. Security Considerations

  • Sanitize user input to prevent SQL Injection.
  • Use prepared statements in SQL queries.
  • Validate AJAX requests to prevent bots from voting.

Congratulations! 🎉 You have successfully built a poll system using jQuery and AJAX. This can be extended to support:

  • User authentication-based voting
  • Multiple-choice questions
  • More advanced result analytics

Would you like help extending this project further?

Leave a Reply

Your email address will not be published. Required fields are marked *