Home  >  Article  >  Backend Development  >  jQuery+Ajax+PHP implements "like" rating function code_PHP tutorial

jQuery+Ajax+PHP implements "like" rating function code_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:11:57726browse

This article will introduce to you a jQuery+Ajax+PHP code to implement the "like" rating function. When the user clicks the red heart button on the picture he likes on the page, the front-end page sends an ajax request to the background. After the background PHP program receives the request, Check whether there is already a click record of the user in the IP library. If not, add the corresponding value by 1 and write the user's IP information into the IP library. Otherwise, the user will be told that he has "liked it".


Database design

First prepare two tables. The pic table saves picture information, including the name, path and total number of "likes" of the picture. Pic_ip records the user's clicks on likes. IP data.

CREATE TABLE IF NOT EXISTS `pic` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pic_name` varchar(60) NOT NULL,
`pic_url` varchar( 60) NOT NULL,
`love` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `pic_ip` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pic_id` int(11) NOT NULL,
`ip` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

index.php

In index.php, we pass PHP Read the image information in the pic table and display it, combined with CSS, to improve the page display effect.

The code is as follows Copy code
 代码如下 复制代码







jQuery+Ajax+PHP实现"喜欢"评级





    include_once("connect.php");
    $sql = mysql_query("select * from pic");
    while($row=mysql_fetch_array($sql)){
    $pic_id = $row['id'];
    $pic_name = $row['pic_name'];
    $pic_url = $row['pic_url'];
    $love = $row['love'];
    ?>
  • <?php echo $pic_name;?>




< meta name="keywords" content="jquery">jQuery+Ajax+PHP to achieve "like" rating</ title><link rel="stylesheet" type="text/css" href="../css/main.css" /><script type="text/javascript" src= "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script type="text/javascript">$(function(){$("p a").click(function(){var love = $(this);var id = love.attr("rel"); love.fadeOut(300);$.ajax({type:"POST",url:"love.php",data:"id="+id, cache:false,success:function(data){love.html(data);love.fadeIn(300);}}); return false;});});</script><style type="text/css">.clear{clear:both}.list{width:760px; margin:20px auto}.list li{float:left; width:360px; height:280px; margin:10px; position:relative}.list li p{position: absolute; top:0; left:0; width:360px; height:24px; line-height:24px; background:#000; opacity:.8;filter:alpha(opacity=80);}.list li p a{padding-left:30px; height:24px; background:url(images/heart.png) no-repeat 4px -1px;color:#fff; font-weight:bold; font-size:14px}. list li p a:hover{background-position:4px -25px;text-decoration:none}</style></head><body><div id="main"><ul class="list"><?php<🎜>include_once("connect.php");<🎜> $sql = mysql_query("select * from pic");<🎜>while($row=mysql_fetch_array($sql)){<🎜>$pic_id = $row['id'];<🎜>$pic_name = $row ['pic_name'];<🎜>$pic_url = $row['pic_url'];<🎜>$love = $row['love'];<🎜>?><li><img src="images/<?php echo $pic_url;?>" alt="<?php echo $pic_name;?>"><p><a href="#" title="Me Like" class="img_on" rel="<?php echo $pic_id;?>"><?php echo $love;?></a></p></li> <?php }?></ul></div></body></html></td> </tr> </table> <p>In CSS, we will define the dynamic effect of the mouse sliding towards and away from the red heart button, and position the button. </p> <table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> The code is as follows</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8372 ')">Copy code</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id="copy8372"> <table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8372')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id="copy8372"><p>.list{width:760px; margin:20px auto} <br>.list li{float:left; width:360px; height:280px; margin:10px; position:relative} <br>.list li p{position:absolute; top:0; left:0; width:360px; height:24px; line-height:24px;  <br>background:#000; opacity:.8;filter:alpha(opacity=80);} <br>.list li p a{padding-left:30px; height:24px; background:url(images/heart.png) no-repeat  <br>4px -1px;color:#fff; font-weight:bold; font-size:14px} <br>.list li p a:hover{background-position:4px -25px;text-decoration:none} </p></td> </tr> </table>.list{width:760px; margin:20px auto} <br>.list li{float:left; width:360px; height:280px; margin:10px; position:relative} <br>.list li p{position:absolute; top:0; left:0; width:360px; height:24px; line-height:24px; <br>background:#000; opacity:.8;filter :alpha(opacity=80);} <br>.list li p a{padding-left:30px; height:24px; background:url(images/heart.png) no-repeat <br>4px -1px; color:#fff; font-weight:bold; font-size:14px} <br>.list li p a:hover{background-position:4px -25px;text-decoration:none} <p></p> </td> </tr> </table>jQuery code<p></p>When the user clicks the red heart button on the picture he likes, an ajax request is sent to the background love.php. After the request response is successful, the original is updated. numerical value. <table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9358')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id="copy9358"><p>$(function(){ <br>    $("p a").click(function(){ <br>        var love = $(this); <br>        var id = love.attr("rel"); //对应id <br>        love.fadeOut(300); //渐隐效果 <br>        $.ajax({ <br>            type:"POST", <br>            url:"love.php", <br>            data:"id="+id, <br>            cache:false, //不缓存此页面 <br>            success:function(data){ <br>                love.html(data); <br>                love.fadeIn(300); //渐显效果 <br>            } <br>        }); <br>        return false; <br>    }); <br>}); </p></td> </tr> </table> <table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> The code is as follows</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9358 ')">Copy code</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id="copy9358">$(function(){ <br> $("p a").click(function(){ <br> var love = $(this); <br> var id = love.attr("rel"); //corresponding id <br> love.fadeOut(300); //fade out effect <br> $.ajax({ <br> type: "POST" , <br> url: "love.php", <br> data: "id ="+id, <br> cache: false, // not cache this page <br> SUCCESS: Function (data) { <br>                 love.html(data); > }); <br>}); </td> </tr> </table> <p>love.php</p> <p>The background love.php receives the ajax request from the front end, and based on the submitted image id value, checks whether there is a click record of the user's IP in the IP table. If so, it tells the user that it has been " "I liked it", otherwise, perform the following operations: </p> <p> 1. Update the corresponding image love field value in the image table and add 1 to the value. </p> <p>2. Write the user’s IP information into the pic_ip table to prevent users from clicking repeatedly. </p> <p>3. Get the updated love value, which is the total number of users who like the picture, and output the total to the front-end page. </p> <table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> The code is as follows<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8135')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id="copy8135"> <p><?php<br />$host="localhost";<br />$db_user="root";<br />$db_pass="";<br />$db_name="demo";<br />$timezone="Asia/Shanghai";</p><p>$link=mysql_connect($host,$db_user,$db_pass);<br />mysql_select_db($db_name,$link);<br />mysql_query("SET names UTF8");<br />?></p> <p> </p> <p> </p> <p><?php<br />include_once("connect.php");</p><p>$ip = get_client_ip();<br />$id = $_POST['id'];<br />if(!isset($id) || empty($id)) exit;</p><p>$ip_sql=mysql_query("select ip from pic_ip where pic_id='$id' and ip='$ip'");<br />$count=mysql_num_rows($ip_sql);<br />if($count==0){<br />$sql = "update pic set love=love+1 where id='$id'";<br />mysql_query( $sql);<br />$sql_in = "insert into pic_ip (pic_id,ip) values ('$id','$ip')";<br />mysql_query( $sql_in);<br />$result = mysql_query("select love from pic where id='$id'");<br />$row = mysql_fetch_array($result);<br />$love = $row['love'];<br />echo $love;<br />}else{<br />echo "喜欢过了..";<br />}</p><p>//获取用户真实IP<br />function get_client_ip() {<br />if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))<br />$ip = getenv("HTTP_CLIENT_IP");<br />else<br />if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))<br />$ip = getenv("HTTP_X_FORWARDED_FOR");<br />else<br />if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))<br />$ip = getenv("REMOTE_ADDR");<br />else<br />if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))<br />$ip = $_SERVER['REMOTE_ADDR'];<br />else<br />$ip = "unknown";<br />return ($ip);<br />}<br />?></p> </td> </tr> </table> </td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8135' )">Copy code<p> <br> </p> </td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id="copy8135"><?php</td>$host="localhost";</tr>$db_user="root";</table>$db_pass="";<br>$db_name="demo"; </p>$timezone="Asia/Shanghai";<p align="left"><div style="display:none;">$link=mysql_connect($host,$db_user,$db_pass);<span id="url" itemprop="url">mysql_select_db($db_name,$link);</span>mysql_query( "SET names UTF8");<span id="indexUrl" itemprop="indexUrl">?><span id="isOriginal" itemprop="isOriginal"> </span><span id="isBasedOnUrl" itemprop="isBasedOnUrl"> </span><span id="genre" itemprop="genre"><?php</span>include_once("connect.php");<span id="description" itemprop="description"> </span>$ip = get_client_ip();</div>$id = $_POST['id'];</p>if(!isset($id) || empty($id)) exit;</div><div class="art_confoot">$ip_sql=mysql_query("select ip from pic_ip where pic_id='$id' and ip='$ip'");</div>$count=mysql_num_rows($ip_sql);<🎜>if($count==0 ){<🎜>$sql = "update pic set love=love+1 where id='$id'";<🎜>mysql_query( $sql);<🎜>$sql_in = "insert into pic_ip (pic_id,ip) values ​​('$id','$ip')";<🎜>mysql_query( $sql_in);<🎜>$result = mysql_query("select love from pic where id='$id'");<🎜>$ row = mysql_fetch_array($result);<🎜>$love = $row['love'];<🎜>echo $love;<🎜>}else{<🎜>echo "I liked it..";<🎜> }<🎜><🎜>//Get the user’s 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 get_client_ip() function in the code is used to obtain the user’s real IP http://www.bkjia.com/PHPjc/444603.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444603.htmlTechArticleThis article will introduce to you a jQuery+Ajax+PHP code to implement the "like" rating function. Users click on the page When you click the red heart button on the picture you like, the front-end page sends a message to the background... </span> </td> </tr> </table></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="Multiple ways to create shortcuts to desktop from web pages_PHP tutorial" href="http://m.php.cn/faq/305928.html">Multiple ways to create shortcuts to desktop from web pages_PHP tutorial</a></span><span>Next article:<a class="dBlack" title="Multiple ways to create shortcuts to desktop from web pages_PHP tutorial" href="http://m.php.cn/faq/305930.html">Multiple ways to create shortcuts to desktop from web pages_PHP tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="http://m.php.cn/"><b class="icon1"></b><p>Home</p></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="http://m.php.cn/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="http://m.php.cn/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="http://m.php.cn/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="http://m.php.cn/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="http://m.php.cn/" >Home</a></div><div class="swiper-slide"><a href="http://m.php.cn/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="http://m.php.cn/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="http://m.php.cn/course.html" >Course</a></div><div class="swiper-slide"><a href="http://m.php.cn/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="http://m.php.cn/xiazai" >Download</a></div><div class="swiper-slide"><a href="http://m.php.cn/game" >Game</a></div><div class="swiper-slide"><a href="http://m.php.cn/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs" ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan " href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a onclick="javascript:;" class="language course-right-orders chooselan chooselanguage" href="javascript:;"><span>English</span><span>(EN)</span></a><a onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan " href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a><a onclick="javascript:setlang('ja');" class="language course-right-orders chooselan " href="javascript:;"><span>日本語</span><span>(JA)</span></a><a onclick="javascript:setlang('ko');" class="language course-right-orders chooselan " href="javascript:;"><span>한국어</span><span>(KO)</span></a><a onclick="javascript:setlang('ms');" class="language course-right-orders chooselan " href="javascript:;"><span>Melayu</span><span>(MS)</span></a><a onclick="javascript:setlang('fr');" class="language course-right-orders chooselan " href="javascript:;"><span>Français</span><span>(FR)</span></a><a onclick="javascript:setlang('de');" class="language course-right-orders chooselan " href="javascript:;"><span>Deutsch</span><span>(DE)</span></a></div></div><script> var swiper = new Swiper('.nphpNavSwiper1', { slidesPerView : 'auto', observer: true,//修改swiper自己或子元素时,自动初始化swiper observeParents: true,//修改swiper的父元素时,自动初始化swiper }); </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>