Home Web Front-end JS Tutorial PHP combined with jQuery to implement red and blue voting function special effects_jquery

PHP combined with jQuery to implement red and blue voting function special effects_jquery

May 16, 2016 pm 03:49 PM

This is a very practical voting example, applied in a two-party viewpoint voting scenario. Users can choose to vote for the party that represents their own views. This article takes the voting of the red and blue parties as an example. Through front-end and back-end interaction, it intuitively displays the number and proportion of votes cast by the red and blue parties. It is widely used.

This article is a comprehensive knowledge application article, which requires you to have basic knowledge of PHP, jQuery, MySQL, html and css. This article has made appropriate improvements based on the article "The "Like" and "Dislike" Voting Function Implemented by PHP MySql jQuery" and shares the data table. You can click to learn about this article first.

HTML

We need to display the views of the red and blue parties on the page, as well as the corresponding number and proportion of votes, as well as hand pictures for voting interaction. In this example, #red and #blue represent the red and blue parties respectively. .redhand and .bluehand are used to make hand-shaped voting buttons, .redbar and .bluebar show the proportion of red and blue, and #red_num and #blue_num show the number of votes from both parties.

 
<div class="vote"> 
  <div class="votetitle">您对脚本之家提供的文章的看法?</div> 
  <div class="votetxt">非常实用<span>完全看不懂</span></div> 
  <div class="red" id="red"> 
    <div class="redhand"></div> 
    <div class="redbar" id="red_bar"> 
      <span></span> 
      <p id="red_num"></p> 
    </div> 
  </div> 
  <div class="blue" id="blue"> 
    <div class="bluehand"></div> 
    <div class="bluebar" id="blue_bar"> 
      <span></span> 
      <p id="blue_num"></p> 
    </div> 
  </div> 
</div> 
Copy after login

CSS

Use CSS to beautify the page, load background images, determine relative positions, etc. You can directly copy the following code and make slight modifications in your own 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} 
Copy after login

jQuery

When the hand button is clicked, jQuery's $.getJSON() is used to send an Ajax request to the background php. If the request is successful, the json data returned by the background will be obtained, and jQuery will process the json data. The following function: getdata(url,sid), passes two parameters. URL is the backend PHP address of the request, and sid represents the current voting topic ID. In this function, the json data returned includes the number of votes from both red and blue parties, and The ratio of both parties, calculate the width of the proportion bar based on the ratio, and display the voting effect asynchronously interactively.

 
function getdata(url,sid){ 
  $.getJSON(url,{id:sid},function(data){ 
    if(data.success==1){ 
      var w = 208; //定义比例条的总宽度 
      //红方投票数 
      $("#red_num").html(data.red); 
      $("#red").css("width",data.red_percent*100+"%"); 
      var red_bar_w = w*data.red_percent-10; 
      //红方比例条宽度 
      $("#red_bar").css("width",red_bar_w); 
      //蓝方投票数 
      $("#blue_num").html(data.blue); 
      $("#blue").css("width",data.blue_percent*100+"%"); 
      var blue_bar_w = w*data.blue_percent; 
      //蓝方比例条宽度 
      $("#blue_bar").css("width",blue_bar_w); 
    }else{ 
      alert(data.msg); 
    } 
  }); 
} 
Copy after login

When the page is loaded for the first time, getdata() is called, and then click to vote for the red team or vote for the blue team to also call getdata(), but the parameters passed are different. Note that the parameter sid in this example is set to 1, which is set based on the id in the data table. Developers can read the accurate id based on the actual project.

 
$(function(){ 
  //获取初始数据 
  getdata("vote.php",1); 
  //红方投票 
  $(".redhand").click(function(){ 
    getdata("vote.php&#63;action=red",1); 
  }); 
  //蓝方投票 
  $(".bluehand").click(function(){ 
    getdata("vote.php&#63;action=blue",1); 
  }); 
}); 
Copy after login

PHP

The front end requests vote.php in the background, and vote.php will connect to the database and call related functions based on the received parameters.

 
include_once("connect.php"); 
 
$action = $_GET['action']; 
$id = intval($_GET['id']); 
$ip = get_client_ip();//获取ip 
 
if($action=='red'){//红方投票 
  vote(1,$id,$ip); 
}elseif($action=='blue'){//蓝方投票 
  vote(0,$id,$ip); 
}else{//默认返回初始数据 
  echo jsons($id); 
} 
Copy after login

The function vote($type,$id,$ip) is used to make a voting action. $type represents the voting party, $id represents the ID of the voting topic, and $ip represents the user's current IP. First, based on the user's current IP, query whether the current IP record already exists in the voting record table votes_ip. If it exists, it means that the user has voted. Otherwise, update the number of votes for the red side or the blue side, and write the current user voting record 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){//还没有投票 
    if($type==1){//红方 
      $sql = "update votes set likes=likes+1 where id=".$id; 
    }else{//蓝方 
      $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'] = '操作失败,请重试'; 
      echo json_encode($arr); 
    } 
  }else{ 
    $arr['success'] = 0; 
    $arr['msg'] = '已经投票过了'; 
    echo json_encode($arr); 
  } 
} 
Copy after login

The function jsons($id) queries the number of votes for the current id, calculates the proportion and returns 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); 
} 
Copy after login

The article also involves the function of obtaining the user’s real IP: get_client_ip(). Click here to see the relevant code: http://www.jb51.net/article/38940.htm

MySQL

Finally, paste the Mysql data table. The votes table is used to record the total number of votes from both red and blue parties, and the votes_ip table is used to store the user’s voting IP 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; 
Copy after login

As a reminder, if the downloaded demo cannot run, please first check whether the database connection configuration is correct. Okay, stop saying a few words and come and vote:

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles