Home Web Front-end JS Tutorial jQuery PHP star rating implementation method_jquery

jQuery PHP star rating implementation method_jquery

May 16, 2016 pm 03:37 PM

The effect achieved in this example:

Transition animation showing rating action.
Update average scores and user-rated scores in a timely manner.
The background restricts users from repeating rating operations and displays them in a timely manner on the front end.
XHTML

<div class="rate"> 
  <div class="big_rate"> 
    <span rate="2"> </span> 
    <span rate="4"> </span> 
    <span rate="6"> </span> 
    <span rate="8"> </span> 
    <span rate="10"> </span> 
    <div style="width:45px;" class="big_rate_up"></div> 
  </div> 
  <p><span id="s" class="s"></span><span id="g" class="g"></span></p> 
  <div id="my_rate"></div> 
</div> 
Copy after login

The HTML structure is divided into gray star div#big_rate, bright star div#big_rate_up, scores span#s and span#g and prompt information div#my_rate.
CSS

.rate{width:600px; margin:100px auto; font-size:14px; position:relative; padding:10px 0;} 
.rate p {margin:0; padding:0; display:inline; height:40px; overflow:hidden; position:absolute; 
top:0; left:100px; margin-left:140px;} 
.rate p span.s {font-size:36px; line-height:36px; float:left; font-weight:bold; color:#DD5400;} 
.rate p span.g {font-size:22px; display:block; float:left; color:#DD5400;} 
.big_rate {width:140px; height:28px; text-align:left; position:absolute; top:3px; left:85px; 
display:inline-block; background:url(star.gif) left bottom repeat-x;} 
.big_rate span {display:inline-block; width:24px; height:28px; position:relative; z-index:1000; 
 cursor:pointer; overflow:hidden;} 
.big_rate_up {width:140px; height:28px; position:absolute; top:0; left:0; 
 background:url(star.gif) left top;} 
#my_rate{ position:absolute; margin-top:40px; margin-left:100px} 
#my_rate span{color:#dd5400; font-weight:bold} 
Copy after login

jQuery
Let's first write a function get_rate() to handle the front-end interaction of scoring.

function get_rate(rate){ 
  ....do some thing 
} 
Copy after login

The function get_rate(rate) needs to pass a parameter: rate, which is used to represent the average score. Next, the parameter rate must be processed in the function:

rate=rate.toString(); 
  var s; 
  var g; 
  $("#g").show(); 
  if (rate.length>=3){ 
    s=10;  
    g=0; 
    $("#g").hide(); 
  }else if(rate=="0"){ 
    s=0; 
    g=0; 
  }else{ 
    s=rate.substr(0,1); 
    g=rate.substr(1,1); 
  } 
  $("#s").text(s); 
  $("#g").text("."+ g); 
Copy after login

Convert the average score rate into a format such as: 6.8, which is used to display the average score on the front end.
Next, when we slide the mouse towards the star, an animation effect will be generated. The width of the bright star will change as the mouse slides, and the score value will also change accordingly.

$(".big_rate_up").animate({width:(parseInt(s)+parseInt(g)/10) * 14,height:26},1000); 
$(".big_rate span").each(function(){ 
    $(this).mouseover(function(){ 
      $(".big_rate_up").width($(this).attr("rate") * 14 ); 
      $("#s").text($(this).attr("rate")); 
      $("#g").text(""); 
    }).click(function(){ 
      ...ajax异步提交给后台处理 
    }) 
}) 
Copy after login

The above code is not difficult to understand. What needs to be explained is why the width should be multiplied by 14? Because the width of the picture is 28, a total of 5 pictures represents a full score of 10 points. The calculated width of the unit score (1 point) is (5*28)/10=14.
When clicking the star, you need to send an ajax request to the background address to interact with the background.

var score = $(this).attr("rate"); 
$("#my_rate").html("您的评分:<span>"+score+"</span>"); 
  $.ajax({ 
     type: "POST", 
     url: "post.php", 
     data:"score="+score, 
     success: function(msg){ 
      if(msg==1){ 
        $("#my_rate").html("<span>您已经评过分了!</span>"); 
      }else if(msg==2){ 
        $("#my_rate").html("<span>您评过分了!</span>"); 
      }else{ 
        get_rate(msg); 
      } 
    } 
  }); 
Copy after login

It is not difficult to see that when a star is clicked, the front end sends an ajax request to the background program post.php in POST mode, passing the parameter score, which is the score. After determining the score, the background program performs corresponding processing and sends different processing information to the front end based on the processing results.
And don’t forget, the score should be restored when the mouse leaves the star:

$(".big_rate").mouseout(function(){ 
  $("#s").text(s); 
  $("#g").text("."+ g); 
  $(".big_rate_up").width((parseInt(s)+parseInt(g)/10) * 14); 
}) 
Copy after login

The function get_rate() is completed, we only need to call it when the page is loaded.

$(function(){ 
  get_rate(88); 
}); 
Copy after login

PHP
The post.php program needs to process: receiving the score value sent by the front end, determining the user IP and scoring time through cookies, and preventing repeated scoring.

include_once ('connect.php'); //连接数据库 
$score = $_POST['score']; 
if (isset ($score)) { 
  $cookiestr = getip(); 
  $time = time(); 
  if (isset ($_COOKIE['person']) && $_COOKIE['person'] == $cookiestr) { 
    echo "1"; 
  } 
  elseif (isset ($_COOKIE['rate_time']) && ($time -intval($_COOKIE['rate_time'])) < 600) { 
    echo "2"; 
  } else { 
    $query = mysql_query("update raty set voter=voter+1,total=total+'$score' where id=1"); 
    $query = mysql_query("select * from raty where id=1"); 
    $rs = mysql_fetch_array($query); 
    $aver = $rs['total'] / $rs['voter']; 
    $aver = round($aver, 1) * 10; 
    //设置COOKIE 
    setcookie("person", $cookiestr, time() + 3600); 
    setcookie("rate_time", time(), time() + 3600); 
    echo $aver; 
  } 
} 
Copy after login

Obviously, when the user submits a rating once, the program will record the user's IP and time to prevent repeated submissions. When the user rates for the first time, the program performs operations, adds the rating value to the data table, and calculates The average score is returned to the frontend call.
The method getip() on how to obtain the user's IP is already available in the DEMO. It will not be introduced here. Please download it yourself.
Finally, attach the mysql table structure:

CREATE TABLE IF NOT EXISTS `raty` ( 
 `id` int(11) NOT NULL auto_increment, 
 `voter` int(10) NOT NULL default '0' COMMENT '评分次数', 
 `total` int(11) NOT NULL default '0' COMMENT '总分', 
 PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 
Copy after login

The above is the jQuery PHP star rating implementation method. I hope it will be helpful to everyone's learning.

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