Php and jQuery are used to implement the "TOP" and "step on" voting functions. phpjquery

Source: Internet
Author: User
Tags learn php programming

Php and jQuery are used to implement the "TOP" and "step on" voting functions. phpjquery

When we browse a webpage and want to agree or disagree with the content of the webpage, such as the opinions in articles and comments, we can click "TOP" and "step on" on the webpage to vote. The entire interaction process can be implemented asynchronously using ajax to improve user experience.

We must first prepare the mysql DATA table required to run the entire instance. Two tables are required for the instance. The votes table is used to record the number of user votes corresponding to articles or comments, in addition, we write a data entry with id 1 by default for demonstration. The votes_ip table is used to record the IP address of each user vote. The program determines whether the vote is valid based on the user IP address.

Data Table

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; 

HTML

On the page, there are two buttons indicating "TOP" and "Step", namely # dig_up and # dig_down. The buttons record the votes and percentages respectively, intuitively compares the voting results.

<Div class = "digg"> <div id = "dig_up" class = "digup"> <span id = "num_up"> </span> <p> very good, very powerful! </P> <div id = "bar_up" class = "bar"> <span> </span> <I> </div> <div id = "dig_down" class = "digdown"> <span id = "num_down"> </span> <p> too bad! </P> <div id = "bar_down" class = "bar"> <span> </span> <I> </div> <div id = "msg"> </div>

CSS

We use CSS to beautify the page. We use a figure diggs.png to locate different button backgrounds and set the position to locate the positional relationship between each element.

.digg{width:420px; height:120px; margin:80px auto 20px auto; position:relative} #dig_up,#dig_down{width:200px; height:48px; margin:10px; position:relative; border:1px solid #d3d3d3; padding-left:42px; cursor:pointer} .digup{background:url(diggs.png) no-repeat 4px 2px;} .digup_on{background:url(diggs.png) no-repeat 4px -49px;} .digdown{background:url(diggs.png) no-repeat 4px -102px;} .digdown_on{background:url(diggs.png) no-repeat 4px -154px;} #num_up,#num_down{position:absolute; right:6px; top:18px; font-size:20px;} #dig_up p{height:24px; line-height:24px; color:#360} #dig_down p{height:24px; line-height:24px; color:#f30} .bar{width:100px; height:12px; line-height:12px; border:1px solid #f0f0f0; position:relative; text-align:center} .bar span{display:block; height:12px; } .bar i{position:absolute; top:0; left:104px;} #bar_up span{background:#360} #bar_down span{background:#f60} #msg{position:absolute; right:20px; top:40px; font-size:18px; color:#f00} 

JQuery

This example also depends on jQuery, so you must not forget to load the jquery library file first on the page.
First, jQuery needs to process the background image transformed when the mouse slides to the two voting buttons, which is implemented by addClass () and removeClass.

$ (Function () {// when the mouse slides and leaves the voting button, the background style is changed $ ("# dig_up "). hover (function () {$ (this ). addClass ("digup_on") ;}, function () {$ (this ). removeClass ("digup_on") ;}); $ ("# dig_down "). hover (function () {$ (this ). addClass ("digdown_on") ;}, function () {$ (this ). removeClass ("digdown_on") ;}); // initialize the data getdata ("do. php ", 1); // when you click" TOP "$ (" # dig_up "). click (function () {getdata ("do. php? Action = like ", 1) ;}); // click $ (" # dig_down "). click (function () {getdata (" do. php? Action = unlike ", 1 );});});

Then, after loading the page, we need to display the initial voting results, including the number of votes and percentage. We write the operation to get data in a custom function getdata (), and load the data by passing different request addresses and id parameters. In the getdata () function, an ajax request is sent to the URL. Based on the results returned by the background processing, if the voting succeeds, the content of the corresponding elements on the page is changed, including the number of votes and percentage.

Function getdata (url, sid) {$. getJSON (url, {id: sid}, function (data) {if (data. success = 1) {// vote successful $ ("# num_up" ).html (data. like); // display the percentage progress bar effect by controlling the width $ ("# bar_up span" ).css ("width", data. like_percent); $ ("# bar_up I" pai.html (data. like_percent); $ ("# num_down" pai.html (data. unlike); $ ("# bar_down span" ).css ("width", data. unlike_percent); $ ("# bar_down I" pai.html (data. unlike_percent);} else {// failed to vote $ ("# msg" cmd.html(data.msg0000.show(cmd.css ({'opacity ': 1, 'top': '40px '}). animate ({top: '-50px', opacity: 0}, "slow ");}});}

PHP

Data is obtained through do. php to complete, do. php connects to the database based on the parameters passed on the front-end page and enters the "TOP", "Step", and initial data processing modules based on the condition judgment. The following are do. php module code structure:

Include_once ("connect. php "); // connect to the database $ action =$ _ GET ['action']; $ id = 1; $ ip = get_client_ip (); // obtain ip if ($ action = 'like') {// top likes (1, $ id, $ ip);} elseif ($ action = 'unlike ') {// step on likes (0, $ id, $ ip);} else {echo jsons ($ id );}

The likes () function is used to process the "TOP" and "Step" voting modules. First, it is used to determine whether the user's IP address has been voted. If the user's IP address has already been voted, a prompt is returned directly, if the user's IP address does not have a voting record, update the votes table, add the corresponding number of votes to 1, and insert the user's IP record to the votes_ip table. If the operation succeeds, call jsons () output data such as the number of votes and percentage after the vote, otherwise the input operation fails to prompt information.

Function likes ($ 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) {// if ($ type = 1) {// top $ SQL = "update votes set likes = likes + 1 where id = ". $ id;} else {// step on $ 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 {$ msg = $ type = 1? 'You have already exceeded ':' You have already stepped on '; $ arr ['success'] = 0; $ arr ['msg '] = $ msg; echo json_encode ($ arr );}}

The jsons () function is used to read the number of votes for the corresponding id in the votes table, calculate the percentage, and output the information in json format for the front-end page.

function jsons($id){  $query = mysql_query("select * from votes where id=".$id);  $row = mysql_fetch_array($query);  $like = $row['likes'];  $unlike = $row['unlikes'];  $arr['success']=1;  $arr['like'] = $like;  $arr['unlike'] = $unlike;  $like_percent = round($like/($like+$unlike),3)*100;  $arr['like_percent'] = $like_percent.'%';  $arr['unlike_percent'] = (100-$like_percent).'%';    return json_encode($arr); } 

This instance can be applied to common scenarios such as "like", "agree and disagree with comments", and the voting system. It uses Ajax principles to implement front-end interaction. In do. php, The get_client_ip () function is used to obtain the user's real IP address.

The above is all the content of this article. I hope it will help you learn php programming.

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.