PHP Example - AJAX Poll
AJAX Poll
In the example below, we will demonstrate a voting program through which the poll results are displayed without the web page being refreshed.
Do you like PHP and AJAX?
Example Explanation - HTML Page
When the user selects one of the options above, a function named "getVote()" is executed. This function is triggered by the "onclick" event.
poll.html The file code is as follows:
Runoob Tutorial(runoob.com)
你喜欢 PHP 和 AJAX 吗?
The getVote() function performs the following steps:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send a request to the file on the server
- Note the parameter (q) appended to the end of the URL (containing the dropdown list contents)
PHP File
The server page called via JavaScript above is named "poll_vote.php" PHP file:
结果:
是:
%
否:
%
When the selected value is sent from JavaScript to the PHP file, the following happens:
- Get the content of the "poll_result.txt" file
- Put the file content into a variable and add 1 to the selected variable
- Write the result to the "poll_result.txt" file
- Output the graphical poll results
Text File
Text file (poll_result.txt) stores data from the voting program.
The data it stores is as follows:
3||4
The first number indicates the number of "Yes" votes, and the second number indicates the number of "No" votes.
**Note:** Please remember to allow only your web server to edit this text file.Do notgive access to others, except the web server (PHP).