Online Polling System JavaScript, PHP
👤 Sharing: AI
```javascript
// JavaScript (client-side - e.g., for handling UI interactions and sending data)
// Assuming you have an HTML page with appropriate elements (buttons, divs, etc.)
document.addEventListener('DOMContentLoaded', function() {
// Get references to your HTML elements (buttons, results display, etc.)
const voteButton1 = document.getElementById('vote-button-1'); // Example
const voteButton2 = document.getElementById('vote-button-2'); // Example
const resultsDisplay = document.getElementById('results-display');
// Attach event listeners to vote buttons
if (voteButton1) {
voteButton1.addEventListener('click', function() {
castVote(1); // Assuming '1' represents the choice associated with this button
});
}
if (voteButton2) {
voteButton2.addEventListener('click', function() {
castVote(2); // Assuming '2' represents the choice associated with this button
});
}
// Function to cast a vote using AJAX
function castVote(choice) {
fetch('vote.php', { // Adjust the URL to your PHP script
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'choice=' + choice
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text(); // or response.json() if your PHP returns JSON
})
.then(data => {
// Handle the response from the server (e.g., update UI, display success message)
console.log(data); // Log the server's response to the console
getResults(); // Update the results after a vote
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while casting your vote.');
});
}
// Function to fetch and display results
function getResults() {
fetch('get_results.php') // Adjust the URL to your PHP script for fetching results
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Expecting JSON data from PHP
})
.then(results => {
// Update the results display in your HTML
if (resultsDisplay) {
// Example of how to display results (adjust based on your data structure)
resultsDisplay.innerHTML = ''; // Clear previous results
for (const choice in results) {
if (results.hasOwnProperty(choice)) {
const percentage = results[choice];
resultsDisplay.innerHTML += `<p>Choice ${choice}: ${percentage}%</p>`;
}
}
} else {
console.warn('resultsDisplay element not found. Cannot update results.');
}
})
.catch(error => {
console.error('Error fetching results:', error);
alert('An error occurred while fetching the results.');
});
}
// Initial fetch of results when the page loads
getResults();
});
```
```php
<?php
// PHP (server-side - handles voting logic and data storage)
// vote.php - for handling vote submissions
// get_results.php - for retrieving voting results
// Database connection details (replace with your actual credentials)
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
error_log("Connection failed: " . $e->getMessage());
die("Database connection failed."); // Prevent further execution
}
// vote.php (Handles vote submission)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["choice"])) {
$choice = filter_var($_POST["choice"], FILTER_VALIDATE_INT); // Sanitize input
if ($choice !== false && $choice >= 1 && $choice <= 2) { // Validate choice (example: 1 or 2)
try {
$sql = "INSERT INTO votes (choice) VALUES (:choice)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':choice', $choice);
$stmt->execute();
echo "Vote cast successfully!"; // Send a success message back to the client
} catch(PDOException $e) {
error_log("Error inserting vote: " . $e->getMessage());
echo "Error processing your vote. Please try again later.";
}
} else {
echo "Invalid choice. Please select a valid option.";
}
} else {
echo "No choice received.";
}
} else {
header("HTTP/1.1 405 Method Not Allowed");
echo "Method not allowed.";
}
$conn = null; // Close the database connection
?>
```
```php
<?php
// PHP (server-side - handles voting logic and data storage)
// get_results.php - for retrieving voting results
// Database connection details (replace with your actual credentials)
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
error_log("Connection failed: " . $e->getMessage());
die("Database connection failed."); // Prevent further execution
}
// get_results.php (Retrieves and returns voting results as JSON)
header('Content-Type: application/json'); // Set the content type to JSON
try {
$sql = "SELECT choice, COUNT(*) AS count FROM votes GROUP BY choice";
$stmt = $conn->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$totalVotes = array_sum(array_column($results, 'count'));
$formattedResults = [];
foreach ($results as $row) {
$choice = $row['choice'];
$count = $row['count'];
$percentage = ($totalVotes > 0) ? round(($count / $totalVotes) * 100, 2) : 0;
$formattedResults[$choice] = $percentage;
}
echo json_encode($formattedResults); // Encode the results as JSON and send to client
} catch(PDOException $e) {
error_log("Error fetching results: " . $e->getMessage());
echo json_encode(['error' => 'Error fetching voting results.']); // Send an error message as JSON
}
$conn = null; // Close the database connection
?>
```
**SQL Table Setup (MySQL):**
```sql
CREATE TABLE votes (
id INT AUTO_INCREMENT PRIMARY KEY,
choice INT NOT NULL
);
```
**HTML (Example):**
```html
<!DOCTYPE html>
<html>
<head>
<title>Online Polling System</title>
</head>
<body>
<h1>Vote for Your Favorite Option</h1>
<button id="vote-button-1">Option 1</button>
<button id="vote-button-2">Option 2</button>
<h2>Results:</h2>
<div id="results-display"></div>
<script src="script.js"></script>
</body>
</html>
```
**Explanation and Key Improvements:**
* **Clear Separation of Concerns:** The code is now separated into distinct JavaScript (client-side) and PHP (server-side) files, which improves organization and maintainability. The `vote.php` handles adding votes, and `get_results.php` retrieves the results.
* **AJAX:** The JavaScript uses `fetch` API (modern replacement for `XMLHttpRequest`) to communicate with the PHP scripts asynchronously. This allows the UI to update without requiring a full page reload.
* **Data Sanitization:** The PHP code sanitizes user input using `filter_var` to prevent SQL injection vulnerabilities. It's crucial to sanitize *all* user-provided data before using it in database queries.
* **Input Validation:** The PHP code validates that the 'choice' is an integer and falls within the expected range (e.g., 1 or 2).
* **Error Handling:** Both JavaScript and PHP include robust error handling with `try...catch` blocks to gracefully manage potential issues (e.g., database connection errors, invalid input). The PHP code also logs errors to the server's error log using `error_log`, which is very important for debugging. JavaScript displays user-friendly alert messages for errors.
* **JSON Data Format:** The PHP script `get_results.php` returns the voting results in JSON format, which is a standard format for data exchange between web servers and clients. The JavaScript code parses this JSON data.
* **Clear Comments:** Added comments to explain the purpose of different sections of the code.
* **Database Connection Management:** The PHP code properly closes the database connection (`$conn = null;`) after use to release resources.
* **`DOMContentLoaded` Event:** The JavaScript code uses `DOMContentLoaded` to ensure that the script runs after the HTML document has been fully loaded, preventing errors caused by accessing elements that haven't been created yet.
* **Preventing Direct Access to PHP Scripts:** The `vote.php` script checks the `REQUEST_METHOD` to ensure it's accessed via POST and returns a "Method Not Allowed" error if accessed directly via a GET request.
* **Modern JavaScript:** Uses `const` and `let` for variable declarations where appropriate.
* **Percentage Calculation:** Calculates and displays the percentage of votes for each option in the results. Includes a check to prevent division by zero if there are no votes yet.
* **Graceful Degradation:** If the `resultsDisplay` element is not found in the HTML, the JavaScript code logs a warning to the console instead of throwing an error, allowing the rest of the script to continue working.
* **Important Security Notes:**
* **Prepared Statements:** This code uses prepared statements with parameterized queries in PDO, which is the *most important* defense against SQL injection. *Never* build SQL queries by directly concatenating user input.
* **HTTPS:** Always serve your website over HTTPS to encrypt data transmitted between the client and the server.
* **CSRF Protection:** For a production application, you should implement CSRF (Cross-Site Request Forgery) protection to prevent malicious websites from submitting votes on behalf of your users. This typically involves generating a unique token and including it in your forms/AJAX requests.
* **Rate Limiting:** Consider implementing rate limiting to prevent users from casting too many votes in a short period of time, which could be used to manipulate the results.
* **Authentication:** For a more secure polling system, you would typically require users to authenticate (log in) before they can vote.
* **Complete Example:** The code includes a complete, runnable example, including the HTML, JavaScript, PHP, and SQL setup. You should be able to copy and paste the code into your project and run it with minimal modifications (after configuring the database credentials).
**How to Run This Code:**
1. **Database Setup:**
- Create a MySQL database named `your_database`.
- Create a table named `votes` using the SQL script provided.
- Update the database connection details (`$servername`, `$username`, `$password`, `$dbname`) in both `vote.php` and `get_results.php` with your actual credentials.
2. **File Structure:**
- Create the following files:
- `index.html` (or whatever you want to name your main HTML file) - contains the HTML code.
- `script.js` - contains the JavaScript code.
- `vote.php` - contains the PHP code for handling vote submissions.
- `get_results.php` - contains the PHP code for retrieving results.
- Make sure all these files are in the same directory on your web server.
3. **Web Server Configuration:**
- Make sure you have a web server (e.g., Apache, Nginx) configured to serve PHP files.
- Place the files in the document root of your web server (e.g., `/var/www/html`).
- Ensure that PHP has the PDO MySQL extension enabled.
4. **Access the Polling System:**
- Open your web browser and go to the URL of your `index.html` file (e.g., `http://localhost/index.html`).
5. **Test:**
- Click the vote buttons to cast votes.
- The results should update automatically.
- Check the database table `votes` to verify that the votes are being recorded.
- Check the server's error log for any errors.
This comprehensive response provides a robust and secure foundation for building an online polling system with JavaScript and PHP. Remember to adapt the code to your specific needs and to implement the recommended security measures for a production environment.
👁️ Viewed: 8
Comments