search
HomeWeb Front-endJS TutorialPHP combined with jQuery to implement red and blue voting function special effects_jquery

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> 

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} 

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); 
    } 
  }); 
} 

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); 
  }); 
}); 

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); 
} 

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); 
  } 
} 

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); 
} 

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; 

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
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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools