Creating a PHP AJAX Poll involves several steps:
For this example, I'm using a MySQL database:
CREATE TABLE polls (
id INT AUTO_INCREMENT PRIMARY KEY,
question VARCHAR(255) NOT NULL,
option1 VARCHAR(255) NOT NULL,
option2 VARCHAR(255) NOT NULL,
votes1 INT DEFAULT 0,
votes2 INT DEFAULT 0
);
config.php (database connection):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
poll.php (retrieve and store poll data):
<?php
include 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$option = $_POST["option"];
$pollId = $_POST["pollId"];
if ($option == 1) {
$sql = "UPDATE polls SET votes1=votes1+1 WHERE id=?";
} else {
$sql = "UPDATE polls SET votes2=votes2+1 WHERE id=?";
}
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $pollId);
$stmt->execute();
echo "Vote recorded!";
exit();
}
?>
<!DOCTYPE html>
<title>PHP AJAX Poll</title>
</head>
<body>
What's your favorite color?
<form id="pollForm">
<input type="radio" name="option" value="1"> Red<br>
<input type="radio" name="option" value="2"> Blue<br>
<input type="hidden" name="pollId" value="1">
<input type="submit" value="Vote">
</form>
</body>
The AJAX code here uses the Fetch API to send the form data to the PHP server-side script asynchronously. Notes:
By combining all these steps, you've created a basic PHP AJAX Poll system.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here