Examples of support and stepping voting for JQuery Ajax implementations

Source: Internet
Author: User
Tags get ip jquery library

We first prepare to run the required MySQL datasheet 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 default to write a data ID of 1 to demonstrate that the VOTES_IP table is used to record the IP of each user voting, The program determines whether the vote is valid based on the user's IP.

  code is as follows copy code

CREATE TABLE IF not EXISTS ' votes ' (
  ' id ' int (a) NOT NULL auto_increment,
  ' likes ' int (a) NOT null Defau LT ' 0 ',
  ' unlikes ' int (a) not NULL DEFAULT ' 0 ',
  PRIMARY KEY (' id ')
) engine=myisam  DEFA ULT Charset=utf8;
 
 
INSERT into ' votes ' (' id ', ' likes ', ' Unlikes ') VALUES
(1, 30, 10);
 
CREATE TABLE IF not EXISTS ' votes_ip ' (
  ' id ' int (a) not NULL,
  ' vid ' int (ten) not N ull,
  ' IP ' varchar () not NULL
) Engine=myisam DEFAULT Charset=utf8;

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.

The code is as follows Copy Code

<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>
</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.

The code is as follows Copy Code

. 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 ().

The code is as follows Copy Code

$ (function () {
Change the background style when the mouse slides and leaves the voting button
$ ("#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");
});

Initializing data
GetData ("do.php", 1);

When you click Top
$ ("#dig_up"). Click (function () {
GetData ("Do.php?action=like", 1);
});
When you click "Step"
$ ("#dig_down"). Click (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.

The code is as follows Copy Code

function GetData (URL,SID) {
$.getjson (url,{id:sid},function (data) {
if (data.success==1) {//vote successful
$ ("#num_up"). HTML (data.like);
Display percent progress bar effects by controlling width
$ ("#bar_up span"). 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:

connect.php

The code is as follows Copy Code

<?php
Database configuration
$host = "localhost";
$db _user= "root";//user name
$db _pass= "";//Password
$db _name= "Demo";//Database name
$timezone = "Asia/shanghai";

$link =mysql_connect ($host, $db _user, $db _pass);
mysql_select_db ($db _name, $link);
mysql_query ("SET names UTF8");

Header ("content-type:text/html; Charset=utf-8 ");
?>


Include_once ("connect.php");//Connection database

The code is as follows Copy Code
$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.

The code is as follows Copy Code

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) {//has not yet 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);
}
}

//Get user real IP
Function get_client_ip () {
 if (getenv ("Http_client_ip") && strcasecmp (getenv (" Http_client_ip ")," Unknown ")
   $ip = getenv (" Http_client_ip ");
 else
  if ( Getenv ("Http_x_forwarded_for") && strcasecmp (getenv ("Http_x_forwarded_for"), "Unknown"))
     $IP = getenv ("Http_x_forwarded_for");
  else
   if (getenv ("REMOTE_ADDR") && strcasecmp (getenv ("REMOTE_ADDR"), " Unknown "))
     $ip = getenv (" remote_addr ");
   else
     if (Isset ($_server[' remote_addr ')) && $_server[' remote_addr '] && strcasecmp ($_server[' Remote_addr '], "unknown")
      $ip = $_server[' remote_addr '];
     else
      $ip = "Unknown";
 return ($IP);
}

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.

The code is as follows Copy Code

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 obtain the user real IP, this function I have before the article also sent, has been packaged in the code Welcome to download, not posted here.

Related Article

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.