AJAX Poll

PHP AJAX Voting Poll

A very common interactive feature on blogs and forums is a Voting Poll.

In a traditional setup, clicking a "Vote" button reloads the entire page to show the results. By using AJAX, the user clicks to vote, the screen seamlessly transitions to display the updated statistics, and the user's position on the page is entirely undisturbed!


Creating the AJAX Poll

1. The HTML Form

We will create a simple poll asking users what their favorite programming language is.

<div id="poll">
  <h3>Do you prefer PHP or Python?</h3>
  <form>
    <label><input type="radio" name="vote" value="0" onclick="getVote(this.value)"> PHP</label><br>
    <label><input type="radio" name="vote" value="1" onclick="getVote(this.value)"> Python</label>
  </form>
</div>

When a user clicks one of the radio buttons, the onclick event immediately sends the value (0 or 1) to the JavaScript function, which dispatches an AJAX request to the server.

2. The PHP Backend (poll_vote.php)

The PHP script receives the vote and stores it. For simplicity, we will store the results in a simple text file (poll_result.txt), but in a real-world scenario, you would update a database.

<?php
$vote = $_GET['vote'];

// Get content of textfile (format is something like: "10||5" indicating 10 PHP votes and 5 Python votes) $filename = "poll_result.txt"; $content = file($filename);

// Put content in array $array = explode("||", $content[0]); $php_votes = $array[0]; $python_votes = $array[1];

// Increment the correct counter based on the user's vote if ($vote == 0) { $php_votes = $php_votes + 1; } if ($vote == 1) { $python_votes = $python_votes + 1; }

// Insert the new votes back into the text file $insertvote = $php_votes . "||" . $python_votes; $fp = fopen($filename, "w"); fputs($fp, $insertvote); fclose($fp);

// Output a visual result back to the frontend $total = $php_votes + $python_votes; $php_percent = round(100 * round($php_votes / $total, 2)); $python_percent = round(100 * round($python_votes / $total, 2));

echo "<h2>Result:</h2>"; echo "PHP: " . $php_percent . "% (" . $php_votes . " votes)<br>"; echo "Python: " . $python_percent . "% (" . $python_votes . " votes)"; ?>

Once the backend finishes calculating, it returns the generated HTML directly into the original <div id="poll">, replacing the voting form with the live, updated statistics automatically!


Exercise

?

What is the primary User Experience (UX) benefit of using an AJAX poll instead of a traditional form submission?