Traditional Web Polls (without AJAX)
The offer a thorough illustration of a conventional AJAX poll application constructed with PHP, MySQL, and HTML forms.
Here is the structure of the HTML form for voting:
<form action="show_poll.php" method="post">
<p>Select a Politician:<br/>
<input type="radio" name="vote" id="vote_john_smith" value="John Smith" />
<label for="vote_john_smith">John Smith</label><br/>
<input type="radio" name="vote" id="vote_mary_jones" value="Mary Jones" />
<label for="vote_mary_jones">Mary Jones</label><br/>
<input type="radio" name="vote" id="vote_fred_bloggs" value="Fred Bloggs" />
<label for="vote_fred_bloggs">Fred Bloggs</label><br/>
</p>
<button type="submit" name="show_results">Show Reults</button>
</form>
The form data (the chosen vote) is transmitted to the show_poll.php script, which is defined in the action attribute, via an HTTP POST request when the user presses the “Show Results” submit button. The vote data is sent to the PHP script (show_poll.php) either $_POST[‘vote’] or $_REQUEST[‘vote’]. After that, it establishes a connection to the MySQL database, receives the most recent poll results, and modifies the vote total for the chosen candidate. After processing this data, the script provides a bar chart image representing the findings. A complete page reload is required throughout this procedure in order to show the created image and the updated state.
AJAX Poll
There is no comprehensive, detailed code sample of an AJAX-implemented vote poll. They do, however, illustrate the fundamental ideas of AJAX and the elements of a conventional poll, from which the concept of an AJAX poll can be constructed.
An AJAX poll uses JavaScript to collect the user’s vote and deliver it to the server asynchronously rather than submitting the form and reloading the entire page. Like show_poll.php, the server-side PHP script would process the vote (updating the database) and deliver a response, which might be a confirmation or the updated poll results. After receiving this response, the client-side JavaScript code would dynamically alter a particular section of the webpage (such as a displaying the results) without necessitating a page refresh.
Code Example of AJAX Communication
The illustration of AJAX communication in the context of a search feature, even though there isn’t a direct AJAX poll example. The fundamental steps of an AJAX poll are demonstrated in this example: gathering user input, using AJAX to transfer it to a PHP script, and updating the page with the result.
The client-side JavaScript and HTML from the AJAX search sample are shown here:
<html>
<head>
<style>
span {
color: green;
}
</style>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest(); // Creates the XMLHttpRequest object
xmlhttp.onreadystatechange = function() { // Defines the function to handle state changes
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Checks if request is complete and successful
document.getElementById("txtHint").innerHTML = xmlhttp.responseText; // Updates a page element with the server response
}
};
xmlhttp.open("GET", "php_ajax.php?q=" + str, true); // Opens a GET request to the PHP script, passing data
xmlhttp.send(); // Sends the request
}
}
</script>
</head>
<body>
<p><b>Search your favourite tutorials:</b></p>
<form>
<input type = "text" onkeyup = "showHint(this.value)"> <!-- Triggers showHint on input -->
</form>
<p>Entered Course name: <span id="txtHint"></span></p> <!-- Element to be updated -->
</body>
</html>
In this example, when a user fills in the text input box (onkeyup), the JavaScript function showHint() is called. An XMLHttpRequest object is created by this function. When the request’s status changes, it specifies a function (onreadystatechange) to be invoked. The HTML element with the ID “txtHint” is updated with the response text from the server (xmlhttp.responseText) whenever the request is successful (status == 200) and complete (readyState == 4). After that, the function sends a GET request to php_ajax.php with the current input value (str) as a query parameter (q).
This is php_ajax.php, the matching server-side PHP script.
<?php
// Array with names (expanded for better demonstration)
$a = [];
$a[] = "Android";
$a[] = "JavaScript";
$a[] = "PHP";
$a[] = "Python";
$a[] = "SQL";
$a[] = "ZOPL"; // Just for fun!
// Retrieve the 'q' parameter from the request (GET or POST)
// Use isset() to prevent "Undefined index" notices if 'q' is not provided.
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$hint = "";
// Only proceed if the query string is not empty
if ($q !== "") {
$q = strtolower($q); // Convert query to lowercase for case-insensitive matching
$len = strlen($q); // Get the length of the query string
// Iterate through the array of names
foreach($a as $name) {
// Check if the beginning of the name matches the query string (case-insensitive)
// Using stripos() for a more direct check if $name starts with $q
if (stripos($name, $q) === 0) {
// If this is the first hint, just assign the name
if ($hint === "") {
$hint = $name;
} else {
// Otherwise, append with a comma and space
$hint .= ", " . $name;
}
}
}
}
// Send the response back to the client
// If no hint is found or the query was empty, return a default message.
echo $hint === "" ? "Please enter a valid course name" : $hint;
?>
Output
Using $_REQUEST[“q”], this PHP script obtains the q parameter from the request. Then, using the input string q, it looks for matches in a specified array of names. It sends a hint string back to the client at the end.
Applying the Concept to a Poll
Using these guidelines from the make an AJAX poll by:
- Use JavaScript to stop the default form submission or remove the standard action and method elements from the HTML poll form (vote.html).
- Include a JavaScript method that runs when a user hits the “Vote” button or selects a radio button.
- Determine the value of the chosen vote inside this function.
- To send this vote value to a PHP script (such as submit_vote_ajax.php), use XMLHttpRequest (as seen in the search example) or a jQuery AJAX function (such as $.post()).
- The PHP script would update the database (much like the logic in show_poll.php), receive the vote (for example, by using $_POST[‘vote’] or $_REQUEST[‘vote’]), and possibly query for the new results.
- The PHP script would then repeat back the changed results as the response after encoding them (for example, as JSON, as recommended by $.getJSON()).
- This response would be sent to the onreadystatechange callback in client-side JavaScript (or the jQuery success callback).
- Without requiring a complete page reload, the JavaScript would read the response data and update the pertinent HTML elements on the page (for example, by utilising innerHTML as in the search example) to display the updated vote counts or poll results.
An “AJAX Poll” is created by applying the AJAX communication pattern shown in the search example to the process of voting and showing the most recent results from the poll structure.
Because these are the pertinent code examples found in that demonstrate the elements required to theoretically design an AJAX poll, please take note that the code examples offered are for both a standard PHP poll and an AJAX search suggestion feature.