PHP and jQuery to achieve red-blue voting function special effect _ jquery

Source: Internet
Author: User
This article will share with you the voting program completed by jQuery + PHP + mysql. The function is not too complex and the main result is very good, if you have a need, you can refer to this as a very practical voting example, which is applied in the confrontation voting scenario of both parties. Users can select one party to vote on behalf of their own views. This article uses the red and blue sides to vote as an example. Through the frontend and backend interaction, the voting numbers and proportions of the red and blue sides are intuitively displayed, which is widely used.

This is a comprehensive knowledge application article that requires you to have basic knowledge about PHP, jQuery, MySQL, html, and css. This article makes appropriate improvements based on the "TOP" and "stepping on" voting functions implemented by PHP + MySql + jQuery and shares data tables. You can click to learn more about this article first.

HTML

We need to show the views of both parties on the red and blue pages, the number and proportion of votes, and the hand images used for voting interaction, in this example, # red and # blue represent the red and blue sides respectively .. The redhand and. bluehand buttons are used for manual voting. The. redbar and. bluebar display the proportional adjustment between the red and blue sides. # red_num and # blue_num display the voting numbers of both sides.

 

What do you think of the articles provided by the home?

Very practical and hard to understand

CSS

Use CSS to beautify the page, load the background image, and determine the relative location. You can directly copy the following code and make some modifications in your project.

 .vote{width:288px; height:220px; margin:60px auto 20px auto;position:relative} .votetitle{width:100%;height:62px; background:url(icon.png) no-repeat 0 30px; font-size:15px} .red{position:absolute; left:0; top:90px; height:80px;} .blue{position:absolute; right:0; top:90px; height:80px;} .votetxt{line-height:24px} .votetxt span{float:right} .redhand{position:absolute; left:0;width:36px; height:36px; background:url(icon.png) no-repeat -1px -38px;cursor:pointer} .bluehand{position:absolute; right:0;width:36px; height:36px; background:url(icon.png) no-repeat -41px -38px;cursor:pointer} .grayhand{width:34px; height:34px; background:url(icon.png) no-repeat -83px -38px;cursor:pointer} .redbar{position:absolute; left:42px; margin-top:8px;} .bluebar{position:absolute; right:42px; margin-top:8px; } .redbar span{display:block; height:6px; background:red; width:100%;border-radius:4px;} .bluebar span{display:block; height:6px; background:#09f; width:100%;border-radius:4px; position:absolute; right:0} .redbar p{line-height:20px; color:red;} .bluebar p{line-height:20px; color:#09f; text-align:right; margin-top:6px} 

JQuery

When you click the hand button, use jQuery's $. getJSON () sends an Ajax request to php in the background. If the request succeeds, the json data returned by the background is obtained, and jQuery then processes the json data. The following function: getdata (url, sid) is passed with two parameters. The url is the php address in the request background. sid indicates the ID of the current voting topic. In this function, the returned json data includes the number of votes on both sides of red and blue, and the ratio of both sides. The width of the proportion bar is calculated based on the ratio, and the voting effect is displayed asynchronously.

Function getdata (url, sid) {$. getJSON (url, {id: sid}, function (data) {if (data. success = 1) {var w = 208; // defines the total width of the proportional bar // The number of redsquare votes $ ("# red_num" ).html (data. red); $ ("# red" ).css ("width", data. red_percent * 100 + "%"); var red_bar_w = w * data. red_percent-10; // redsquare proportional Bar width $ ("# red_bar" ).css ("width", red_bar_w); // number of blue-side votes $ ("# blue_num" ).html (data. blue); $ ("# blue" ).css ("width", data. blue_percent * 100 + "%"); var blue_bar_w = w * data. blue_percent; // The width of the blue proportional bar $ ("# blue_bar" ).css ("width", blue_bar_w);} else {alert (data. msg );}});}

When the page is loaded for the first time, getdata () is called, and getdata () is also called by clicking vote for the red party or vote for the blue party, but the parameters passed are different. Note that the sid parameter in this example is set to 1 Based on the id in the data table. developers can read the exact id based on the actual project.

$ (Function () {// get the initial data getdata ("vote. php ", 1); // red party vote $ (". redhand "). click (function () {getdata ("vote. php? Action = red ", 1) ;}); // blue party vote $ (". bluehand "). click (function () {getdata (" vote. php? Action = blue ", 1 );});});

PHP

The frontend requests vote. php In the background. vote. php connects to the database based on the received parameters and calls related functions.

Include_once ("connect. php "); $ action = $ _ GET ['action']; $ id = intval ($ _ GET ['id']); $ ip = get_client_ip (); // obtain the ip if ($ action = 'red') {// The red party vote for vote (1, $ id, $ ip );} elseif ($ action = 'blue') {// The blue-party voting vote (0, $ id, $ ip );} else {// default returned initial data echo jsons ($ id );}

The vote ($ type, $ id, $ ip) function is used to perform a voting action. $ type indicates the voting party, $ id indicates the voting topic id, and $ ip indicates the user's current ip address. First, query whether the current IP address record exists in the votes_ip table based on the user's current ip address. If yes, the user has voted. Otherwise, the red or blue voting count is updated, write the voting records of the current user to the votes_ip table to prevent repeated voting.

Function vote ($ type, $ id, $ ip) {$ ip_ SQL = mysql_query ("select ip from votes_ip where vid = '$ id' and ip =' $ ip '"); $ count = mysql_num_rows ($ ip_ SQL); if ($ count = 0) {// No vote yet if ($ type = 1) {// redsquare $ SQL = "update votes set likes = likes + 1 where id = ". $ id;} else {// blue side $ SQL = "update votes set unlikes = unlikes + 1 where id = ". $ id;} mysql_query ($ SQL); $ SQL _in = "insert into votes_ip (vid, ip) values ('$ id',' $ ip ')"; mysql_query ($ SQL _in); if (mysql_insert_id ()> 0) {echo jsons ($ id);} else {$ arr ['success'] = 0; $ arr ['msg '] = 'Operation failed. Please try again'; echo json_encode ($ arr) ;}} else {$ arr ['success'] = 0; $ arr ['msg '] = 'vote passed'; echo json_encode ($ arr );}}

The jsons ($ id) function is used to query the number of votes of the current id, calculate the proportion, and return the json data format for the front-end call.

 function jsons($id){   $query = mysql_query("select * from votes where id=".$id);   $row = mysql_fetch_array($query);   $red = $row['likes'];   $blue = $row['unlikes'];   $arr['success']=1;   $arr['red'] = $red;   $arr['blue'] = $blue;   $red_percent = round($red/($red+$blue),3);   $arr['red_percent'] = $red_percent;   $arr['blue_percent'] = 1-$red_percent;      return json_encode($arr); } 

This article also involves getting the user's real IP function: get_client_ip (), click here to see the relevant code: http://www.jb51.net/article/38940.htm

MySQL

Finally, the Mysql DATA table is attached. The votes table is used to record the total number of votes on both sides of red and blue, and the votes_ip table is used to store the user's voting IP address records.

CREATE TABLE IF NOT EXISTS `votes` (  `id` int(10) NOT NULL AUTO_INCREMENT,  `likes` int(10) NOT NULL DEFAULT '0',  `unlikes` int(10) NOT NULL DEFAULT '0',  PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;   INSERT INTO `votes` (`id`, `likes`, `unlikes`) VALUES (1, 30, 10);  CREATE TABLE IF NOT EXISTS `votes_ip` (  `id` int(10) NOT NULL,  `vid` int(10) NOT NULL,  `ip` varchar(40) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

Again, if the downloaded demo cannot run, check whether the database connection configuration is correct. Let's just say a few words. Come and vote:

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.