Ajax Poll in PHP
Nice pick! An AJAX Poll in PHP is a great way to let users vote and instantly see poll results without reloading the page. Here's a simple, clean version of how to make one.
? How It Works:
User selects an option and clicks "Vote".
JavaScript sends the vote to a PHP script via AJAX.
PHP stores or updates the vote in the database.
AJAX fetches the updated results and displays them live.
?? Step-by-Step Poll System (AJAX + PHP + MySQL)
? 1. MySQL Table
CREATE TABLE poll ( id INT PRIMARY KEY AUTO_INCREMENT, option_name VARCHAR(100), votes INT DEFAULT 0);INSERT INTO poll (option_name, votes) VALUES ('Option A', 0), ('Option B', 0);? 2. HTML + AJAX (index.html)
<!DOCTYPE html><html><head> <title>AJAX Poll</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><h2>What's your choice?</h2><form id="pollForm"> <input type="radio" name="vote" value="1"> Option A<br> <input type="radio" name="vote" value="2"> Option B<br> <button type="submit">Vote</button></form><div id="result"></div><script>$(document).ready(function(){ $('#pollForm').on('submit', function(e){ e.preventDefault(); var vote = $('input[name="vote"]:checked').val(); if (vote) { $.post("vote.php", {vote: vote}, function(data){ $('#result').html(data); }); } else { alert("Please select an option."); } });});</script></body></html>? 3. PHP File to Handle Vote (vote.php)
<?php$connect = new mysqli("localhost", "root", "", "test_db");if (isset($_POST['vote'])) { $vote = (int) $_POST['vote']; // Update vote count $connect->query("UPDATE poll SET votes = votes + 1 WHERE id = $vote"); // Show updated results $result = $connect->query("SELECT * FROM poll"); while ($row = $result->fetch_assoc()) { echo $row['option_name'] . ": " . $row['votes'] . " votes<br>"; }}?>? What Happens:
You vote ? AJAX sends data to
vote.phpPHP updates the database
PHP returns the new result
AJAX updates the page instantly (no reload!)
? You Can Add:
Voting restrictions (IP/cookie-based)
Visual chart with Google Charts or Chart.js
Result percentages
Poll expiration logic