This article mainly introduces PHP combined with Ajax to implement the voting function. Interested friends can refer to it. I hope it will be helpful to everyone.
In this AJAX example, we will demonstrate a voting program, and the results can be obtained without reloading the web page.
This example includes four elements:
① HTML form
② JavaScript
③ PHP page
④ Text file to store the results
1. HTML form
This is an HTML page. It contains a simple HTML form, and a connection to a JavaScript file:
<html> <head> <script src="poll.js"></script> </head> <body> <p id="poll"> <h2 id="Do-nbsp-you-nbsp-like-nbsp-PHP-nbsp-and-nbsp-AJAX-nbsp-so-nbsp-far">Do you like PHP and AJAX so far?</h2> <form> Yes: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"> <br /> No: <input type="radio" name="vote" value="1" onclick="getVote(this.value)"> </form> </p> </body> </html>
Example explanation - HTML form
As you can see, the above HTML page contains a simple HTML form , which has a
element with two radio buttons.
The form works like this:
1. When the user selects "yes" or "no", an event will be triggered
2. When the event is triggered, the getVote() function will be executed
3. Surrounding the form is a
named "poll". When data is returned from the getVote() function, the returned data replaces the form.
2. Text file
The text file (poll_result.txt) stores data from the voting program.
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).
3. JavaScript
JavaScript code is stored in "poll.js" and connected to the HTML document:
var xmlHttp function getVote(int) { xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="poll_vote.php" url=url+"?vote="+int url=url+"&sid="+Math.random() xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("poll"). innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var objXMLHttp=null if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest() } else if (window.ActiveXObject) { objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP") } return objXMLHttp }
Example Explanation: The
stateChanged() and GetXmlHttpObject functions are the same as the examples in the PHP and AJAX requests section.
getVote() function
This function is executed when the user selects "yes" or "no" in the HTML form.
1. Define the url (file name) sent to the server
2. Add parameters (vote) to the url with the content of the input field
3. Add a random number to Prevent the server from using cached files
4. Call the GetXmlHttpObject function to create an XMLHTTP object and tell the object to execute the stateChanged function when a change is triggered
5. Use the given url to open the XMLHTTP object
6. Send an HTTP request to the server
4. PHP page
The server page called by the JavaScript code is a simple PHP file named "poll_vote.php".
<?php $vote = $_REQUEST['vote']; //get content of textfile $filename = "poll_result.txt"; $content = file($filename); //put content in array $array = explode("||", $content[0]); $yes = $array[0]; $no = $array[1]; if ($vote == 0) { $yes = $yes + 1; } if ($vote == 1) { $no = $no + 1; } //insert votes to txt file $insertvote = $yes."||".$no; $fp = fopen($filename,"w"); fputs($fp,$insertvote); fclose($fp); ?> <h2 id="Result">Result:</h2> <table> <tr> <td>Yes:</td> <td> <img src="/static/imghwm/default1.png" data-src="poll.gif" class="lazy" width='<?php echo(100*round($yes/($no+$yes),2)); ?>' height='20'> <?php echo(100*round($yes/($no+$yes),2)); ?>% </td> </tr> <tr> <td>No:</td> <td> <img src="/static/imghwm/default1.png" data-src="poll.gif" class="lazy" width='<?php echo(100*round($no/($no+$yes),2)); ?>' height='20'> <?php echo(100*round($no/($no+$yes),2)); ?>% </td> </tr> </table>
Example explanation:
The selected value is passed from JavaScript, and then what happens:
1. Get the "poll_result.txt" file The content of
Summary
: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
php to implement the check-in function (case)
How to obtain the WeChat public account article page
How to obtain historical messages from WeChat public accounts
The above is the detailed content of PHP combined with Ajax to implement voting function. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)