Example of jQuery ajax support and voting

Source: Internet
Author: User

We will see a lot of websites have a comment or news, there will be a top or step-on function below, so we just need to click it to implement, next I will introduce how to use php + mysql + jquery ajax to implement this function.

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.

The Code is as follows: Copy code

Create table if not exists 'votes '(
'Id' int (10) not null AUTO_INCREMENT,
'Lik' int (10) not null default '0 ',
'Unlik' 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.

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 powerful! </P>
<Div id = "bar_up" class = "bar"> <span> </span> <I> </div>
</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>
<Div id = "msg"> </div>
</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.

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: pixel ;}
# 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.

The Code is as follows: Copy code

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

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.

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 the percentage progress bar by controlling the width
$ ("# Bar_up span" 2.16.css ("width", data. like_percent );
$ ("# Bar_up I" pai.html (data. like_percent );
$ ("# Num_down" ).html (data. unlike );
$ ("# Bar_down span" ).css ("width", data. unlike_percent );
$ ("# Bar_down I" pai.html (data. unlike_percent );
} Else {// failed to vote
$ ("# Msg" ).html(data.msg0000.show().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:

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"); // connect to the database
 

The Code is as follows: Copy code
$ Action = $ _ GET ['action'];
$ Id = 1;
$ Ip = get_client_ip (); // obtain the ip address
 
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.

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) {// No
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 have already exceeded ': 'You have already stepped on ';
$ Arr ['success'] = 0;
$ Arr ['msg '] = $ msg;
Echo json_encode ($ arr );
}
}

 

// Obtain the user's real IP Address
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 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.

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 ['unlik'];
$ 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, there is also a function get_client_ip () used to obtain the real IP address of the user. I have also posted this function before. It has been packaged in the code. You are welcome to download it and will not post it 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.