Use PHP and jquery to achieve "top" and "step" voting function _php instance

Source: Internet
Author: User
Tags comments get ip learn php learn php programming php programming jquery library

When we browse the Web, we want to agree or disagree with the content of the page, such as articles, comments, and then click on the "Top" and "step" in the page to vote. and the entire interaction process, developers can use Ajax asynchronous to achieve, thereby improving the user experience.

We're going to run the MySQL data table for the entire instance, with two tables in the instance, a votes table to record the number of user votes for the corresponding article or comment, and we write a data ID of 1 to demonstrate that the VOTES_IP table is used to record the IP that the user votes each time. The program determines whether the vote is valid based on the user's IP.

Data tables

CREATE TABLE IF not EXISTS ' votes ' ( 
 ' id ' int ') NOT NULL auto_increment, 
 ' likes ' int (a) NOT null DEFAULT ' 0 ', 
    ' unlikes ' int () not NULL default ' 0 ', 
 PRIMARY KEY (' id ') 
) Engine=myisam DEFAULT Charset=utf8; 
 
 
INSERT into ' votes ' (' id ', ' likes ', ' Unlikes ') VALUES 
(1, a); 
 
CREATE TABLE IF not EXISTS ' votes_ip ' ( 
 ' id ' int (+) not null, 
 ' vid ' int (a) not NULL, 
 ' IP ' varchar ' Null 

Html

In the page, there are two "top" and "step" buttons, namely #dig_up and #dig_down, the button recorded the vote number and the percentage of each, very intuitive comparison of the results of the vote.

<div class= "Digg" > 
 <div id= "dig_up" class= "Digup" > 
  <span id= "num_up" ></span> 
  <p> very good, very strong! </p> 
  <div id= "bar_up" class= "bar" ><span></span><i></i></div> 
 </div> 
  <div id= "Dig_down" class= "Digdown" > 
  <span id= "Num_down" ></span> 
  <p > It's so lame! </p> 
  <div id= "Bar_down" class= "Bar" ><span></span><i></i></div> 
 </div> 
 <div id= "MSG" ></div> 

Css

We have to use CSS to beautify the page, we use a graph diggs.png to locate different button backgrounds, and set the position to position the relationships between the elements.

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 relies on jquery, so it must not be forgotten to load the jquery library file in the page first.
First, jquery deals with background images that are transformed when the mouse slides to the two voting buttons, via AddClass () and Removeclass ().

$ (function () { 
 //mouse to slide and exit the voting button, change the background style 
 $ ("#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"); 
  
 Initialization data 
 GetData ("do.php", 1); 
  
 Click on "Top" 
 $ ("#dig_up"). Click (function () { 
  GetData ("Do.php?action=like", 1); 
 }); 
 Click 
 $ ("#dig_down") when clicking "Step." (function () { 
  GetData ("Do.php?action=unlike", 1); 
 }); 
 

We then initialize the data, which is when the page is loaded, to show the initial results that have been voted, including the number of votes and percentages. We write the operation of obtaining the data in a custom function GetData () to complete the loading of the data by passing different request address and ID parameters. function GetData (), send an AJAX request to the URL, depending on the return result of the background processing, and if the vote succeeds, change the corresponding element content in the page, including the number of votes and the percentage.

function GetData (url,sid) { 
 $.getjson (url,{id:sid},function (data) { 
  if (data.success==1) {//voting succeeded 
   $ ("# Num_up "). HTML (data.like); 
   Displays the percentage progress bar effect 
   $ ("#bar_up span") by controlling the width. css ("width", data.like_percent); 
   $ ("#bar_up i"). html (data.like_percent); 
   $ ("#num_down"). HTML (data.unlike); 
   $ ("#bar_down span"). CSS ("width", data.unlike_percent); 
   $ ("#bar_down i"). html (data.unlike_percent); 
  else{//vote failed 
   $ ("#msg"). HTML (DATA.MSG). Show (). CSS ({' Opacity ': 1, ' top ': ' 40px '}). 
   animate ({top: ' -50px ', opacity:0}, "slow"); 
  } 
 ); 

Php

Data acquisition is done through do.php, do.php according to the parameters of the front-end page, connect the database, according to the conditions of the decision to enter the "top", "step" and the initial data processing module, the following is the Do.php module code structure:

Include_once ("connect.php");/Connect database 
 
$action = $_get[' action ']; 
$id = 1; 
$ip = GET_CLIENT_IP ()///Get IP 
 
if ($action = = ' like ') {//Top 
 likes (1, $id, $IP); 
} ElseIf ($action = = ' unlike ') {//Step 
 likes (0, $id, $ip); 
} else{ 
 Echo jsons ($id); 

function likes () is used to handle the "top" and "Step" voting module, the first is to determine whether the user IP has been voted, if the vote is returned directly to the corresponding prompts, if the user IP did not vote to update the votes table, the corresponding vote number plus 1, and then to Votes_ The IP table inserts the user's IP record, and if the operation succeeds, call Jsons () to output the voting number and percentage of the vote, or else enter the message that the operation failed.

function likes ($type, $id, $ip) { 
 $ip _sql=mysql_query ("Select IP from votes_ip where vid= ' $id ' and ip= '"); 
 $count =mysql_num_rows ($ip _sql); 
 if ($count ==0) {//has not been topped 
  if ($type ==1) {//top 
   $sql = "update votes set likes=likes+1 where id=". $id; 
  } else{//step 
   $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've already topped ': ' You've stepped on '; 
  $arr [' success '] = 0; 
  $arr [' msg '] = $msg; 
  echo Json_encode ($arr); 
 } 

The function jsons () is used to read the votes of the corresponding IDs in the votes table and to calculate the percentages, and then output the information in JSON format for use by 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 example can be applied to the common "praise", consent and objection comments, voting system and other scenarios, using the AJAX principle to achieve the front and back-end interaction functions. Do.php also has a function get_client_ip () to get the user's real IP.

The above is the entire content of this article, I hope that you learn PHP programming help.

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.