PHP – AJAX Poll

PHP-AJAX Poll is a technique used to create polls and surveys on a web page, allowing users to vote and see real-time results without requiring a page refresh. AJAX allows web pages to send and receive data with a server without reloading the entire page, while PHP can process this data on the server-side and interact with a database. Here’s an example of how to use AJAX and PHP together to create a poll feature:

  1. HTML/JavaScript code for AJAX:
<div id="poll">
    <h2>What is your favorite color?</h2>
    <form>
        <input type="radio" name="color" value="Red"> Red<br>
        <input type="radio" name="color" value="Green"> Green<br>
        <input type="radio" name="color" value="Blue"> Blue<br>
        <button type="button" id="vote-button">Vote</button>
    </form>
    <div id="poll-results"></div>
</div>
<script>
$(document).ready(function() {
    $('#vote-button').click(function() {
        var color = $('input[name=color]:checked').val();
        $.ajax({
            url: 'vote.php',
            data: { color: color },
            type: 'POST',
            success: function(data) {
                $('#poll-results').html(data);
            }
        });
    });
});
</script>

In this example, we have an HTML form with radio buttons for the poll options and a button for voting. When the user clicks the vote button, an AJAX request is sent to the server using the $.ajax() function from the jQuery library. The url parameter specifies the URL of the PHP script that will process the request, and the data parameter contains the selected poll option as a POST parameter. In the success callback function, we output the poll results as HTML.

  1. PHP code for processing the AJAX request:
<?php
if (isset($_POST['color'])) {
    $color = $_POST['color'];
    // Save vote to database
    // Get poll results from database
    $results = array('Red' => 10, 'Green' => 5, 'Blue' => 3);
    // Output poll results as HTML
    foreach ($results as $option => $count) {
        echo '<p>' . $option . ': ' . $count . '</p>';
    }
}
?>

In this example, we have a PHP script called vote.php that processes the AJAX request. We check if the color parameter is set in the POST data, and if so, we save the vote to a database. We then retrieve the poll results from the database and output them as HTML.

Overall, AJAX Poll is a useful technique for creating interactive polls and surveys on web pages. By allowing users to vote and see real-time results without requiring a page refresh, it can provide a more engaging and dynamic user experience.