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:
- Create a MySQL database to store poll data.
- Develop a PHP script to handle votes and display results.
- Use AJAX to send user votes to the server.
- 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
- Radio Buttons: Each poll option has a radio button with a unique value corresponding to the option ID.
- AJAX Request:
submitVote()
: Sends the selected vote to the server.loadResults()
: Fetches the current poll results on page load.
- 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
- Database Connection: Connects to the MySQL database.
- Vote Submission:
- Checks for a POST request.
- Updates the vote count in the
poll_options
table.
- Fetch Results: Retrieves the current vote count for all options.
- Dynamic Results: Calculates and displays the percentage of votes for each option.
How It Works
- Users select an option and click the “Vote” button.
- An AJAX POST request is sent to
poll.php
with the selected vote. - The PHP script updates the database and returns the updated poll results.
- The
poll-results
div dynamically displays the updated results. - 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
- Real-time Updates: Results display instantly without page reloads.
- Improved User Experience: Smooth and interactive voting process.
- 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.