PHP - AJAX Poll

Creating an AJAX poll in PHP involves building a simple polling system that allows users to vote for a certain option, and then displaying the updated poll results without refreshing the entire page. Here's a basic example of how you can implement an AJAX poll using HTML, JavaScript, and PHP:


1. HTML (index.html):

Create an HTML page that displays the poll options and updates the results using AJAX.

html
<!DOCTYPE html>
<html>
    <head>
        <title>AJAX Poll Example</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
            function vote(option) {
                $.ajax({
                    type: "POST",
                    url: "vote.php",
                    data: { option: option },
                    success: function(response) {
                        $("#poll-results").html(response);
                    }
                });
            }
        </script>
    </head>
    <body>
        <h2>Poll</h2>
        <div id="poll-options">
            <button onclick="vote('option1')">Option 1</button>
            <button onclick="vote('option2')">Option 2</button>
            <!-- Add more options as needed -->
        </div>
            <div id="poll-results">
            <!-- Poll results will be displayed here -->
        </div>
    </body>
</html>

2. PHP (vote.php):

Create a PHP script that handles the voting process and returns updated poll results.

php
<?php
// Assuming you have a database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['option'])) {
    $option = $_POST['option'];

    // Update the vote count in the database
    $sql = "UPDATE poll_options SET votes = votes + 1 WHERE option_name = '$option'";
    $conn->query($sql);
}

// Retrieve poll results from the database
$results = array();
$sql = "SELECT option_name, votes FROM poll_options";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
$results[$row['option_name']] = $row['votes'];
}

// Display poll results
foreach ($results as $option => $votes) {
    echo "$option: $votes votes<br>";
}

$conn->close();
?>

3. Database Table (poll_options):

Create a database table named "poll_options" to store the poll options and their vote counts.

sql
CREATE TABLE poll_options (
    id INT AUTO_INCREMENT PRIMARY KEY,
    option_name VARCHAR(50) NOT NULL,
    votes INT NOT NULL DEFAULT 0
);
INSERT INTO poll_options (option_name) VALUES ('option1'), ('option2');

In this example, users can click on the poll options, and the `vote()` JavaScript function sends an AJAX POST request to the `vote.php` script. The PHP script updates the vote count in the database and retrieves the updated poll results, which are then displayed on the page.


Keep in mind that this is a basic example. In a real-world scenario, you would likely implement more security measures, error handling, and possibly user authentication to prevent abuse of the polling system.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 Previous

AJAX Database | PHP | Java8s

PHP - AJAX Database

Using Ajax to interact with a database in PHP involves sending requests from the client-side using JavaScript, and then handling those requests on the server-side using PHP to perform database operations. Here's a general outline of how you can achieve this:


1. Client-Side Code (JavaScript):

In your HTML file, include JavaScript code that triggers an Ajax request when an event occurs (e.g., form submission). The JavaScript code will send data to the server and handle the response.

html
<script>
    function saveData() {
        var data = {
            name: document.getElementById("name").value,
            email: document.getElementById("email").value
        };
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                var response = xhr.responseText;
                // Handle the response (e.g., show success message)
            }
        };
        xhr.open("POST", "save_data.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("data=" + JSON.stringify(data));
    }
</script>

2. Server-Side Code (PHP):

Create a PHP script (`save_data.php`) that receives the data from the Ajax request, processes it, and performs the necessary database operations. In this example, we'll use MySQL as the database.

php
<?php
// save_data.php

// Assuming you have a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Get the data from the Ajax request
$data = json_decode($_POST['data'], true);

// Sanitize and prepare data for SQL query (to prevent SQL injection)
$name = $conn->real_escape_string($data['name']);
$email = $conn->real_escape_string($data['email']);

// Perform the database insert query
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
    echo "Data saved successfully.";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

In this example, when the `saveData()` function is triggered (e.g., by clicking a button), it sends the data to the `save_data.php` script using a POST request. The PHP script processes the data, sanitizes it to prevent SQL injection, and then performs an SQL query to insert the data into the database.


Remember to properly handle errors, validate user inputs, and implement security measures to protect against potential vulnerabilities, such as SQL injection. Also, consider using modern frameworks and libraries that provide better tools for handling these tasks.





 PreviousNext