PHP development basic tutorial AJAX voting
AJAX voting
In the following example, we will demonstrate a voting program through which the voting results are displayed without refreshing the web page. show.
The page display is shown in the picture on the right
When the user selects one of the above options, a function named "getVote()" will be executed. This function is triggered by the "onclick" event.
This example includes three parts
HTML form
PHP file
TXT file
HTML file:
See 1.php for the source code
php中文网(php.cn) 你喜欢 PHP 和 AJAX 吗?
The above HTML page contains a simple HTML form with two radio buttons in the
The form works like this:
When the user selects "yes" or "no", an event is triggered
When the event is triggered, the getVote() function is executed
Surrounding the form is a
named "poll". When data is returned from the getVote() function, the returned data replaces the form.getVote() function will perform the following steps:
Create XMLHttpRequest object
Created in Function executed when the server response is ready
Send a request to a file on the server
Please note the parameter (q) added to the end of the URL ( Contains the contents of the drop-down list)
PHP file:
The server called by JavaScript in the above paragraph The page is a PHP file named "2.php":
结果:
是: % 否: % When the selected value is sent from JavaScript to the PHP file, what happens:
Get" poll_result.txt" The contents of the file
Put the file contents into the variable and add 1 to the selected variable
Write the result" poll_result.txt" file
Output graphical voting results
##TXT file
The data from the voting program is stored in a text file (3.txt). It looks like this: 0||0 The first number represents a "Yes" vote, and the second number represents a "No" vote.Note: Remember to allow only your web server to edit this text file. Don't let anyone else gain access except the web server (PHP).
##Learning experienceThis example mainly includes the following knowledge points:
-
Form basics: radio button
- ## onclick event: Occurs when the object is clicked
Function call, function value passing
Creation of AJAX XMLHttpRequest object, function executed when the server responds, sending request to the file on the server: See 1-5 for learning experience
HTML DOM getElementById() method: Returns a reference to the first object with the specified ID
PHP related operations on files:
file(): Read the entire file into an array
fopen(): Open the file or URL
fputs(): Write to file
fclose(): Close an open file
Related functions:
htmlspecialchars(): Convert predefined characters into HTML entities
explode(): Break up the string For array