Build a 5-star rating system using jQuery, AJAX, and PHP
The star rating system on the website makes it easy for users to provide feedback and help others make their choices. It provides businesses with feedback on how customers like their products. Star ratings also help build trust in a website and its products.
All major e-commerce sites use ratings to let buyers know the quality they can expect from products.
In this tutorial, I'll show you how to build your own five-star rating system.
Writing HTML and CSS for structure
The first step in the process of building a star rating system is writing the markup, which depends on the elements we want to display on the page.
We definitely want to include the name of the movie in our ratings widget. We also need to display five stars within the widget that users can click to vote. After users vote, we will also display voting data to them.
The following HTML achieves all this:
1 2 3 4 5 6 7 8 9 10 11 |
|
I'm using the Font Awesome library to add the stars. By default, we want the stars to have a black stroke and no fill. fa-regular
Classes do this for us.
We also want the star's color to change to light yellow when the user hovers over it and to orange when the user clicks on the star to indicate that their rating has been is recorded. The following CSS does it all for us:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
Write jQuery to implement interaction
We will now use some jQuery to respond to user events. There are two events we want to track on our star.
Let's start with the mouseover
event, which will turn our hovering star and all of its previous brothers yellow. However, this only happens if the user has not clicked on the star to register to vote. We'll do this by manipulating the Font Awesome star icon's class.
This is the code we need:
1 2 3 4 5 6 |
|
We use a if
statement to check if our currently hovering star has any siblings, and attach the vote-recorded
class. The presence of any such element indicates that the vote was recorded. In this case we don't do any class manipulation.
However, if the vote has not yet been recorded, we will get the current element and all siblings before it and add the fa-solid
and yellow
classes to them. We also remove these classes from all sibling elements that follow the current element.
Now, we will write the jQuery code that handles the click
event. Whenever a user clicks on the fourth star, we know they want to rate the movie four stars. So we record the number of previous brothers and add one to get rating
. We also log the movie_id
to add the rating to the correct movie.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Let's double check if a vote has been recorded for that particular movie. If the vote has not been recorded yet, we add the vote-recorded
class to the currently clicked element and all its previous siblings.
We also use the jQuery post()
method to send voting data to the backend via a POST request. The first parameter is the URL of the PHP script that will handle our request, while the second parameter is the data we want to process.
We also provide callbacks in done()
to further process the data sent to us from the server after our request has been successfully processed.
The following CodePen demo shows what the front-end of our rating system would look like:
Writing PHP to record votes
We will use a MySQL database to store our voting records on the backend. You can use any application you like to manage the database. I'm using phpMyAdmin. The first step here is to create a database, which I will name rating_test
. Now, we will create a table named movie_ ratings
in the database. Run the following SQL query on the database to create the table:
1 2 3 4 5 6 7 |
|
Executing the above statement will create a table named movie_ ratings
, which contains four different columns.
The first one is the auto-incrementing id
, which serves as the primary key for every record we add to the table. The second is movie_id
, which will identify a movie and can contain up to 128 characters. The third one is average_ rating
to store the average of all votes cast so far. The fourth, total_votes
, is used to track the total number of votes cast.
Let’s review the first parameter of the post()
method in the previous section. You will see the string update_atings.php, this is the file we need to create now. This file will contain the PHP code that updates and records the movie's rating.
1 2 3 4 5 6 7 8 |
|
我们首先使用 $_POST
获取 POST 数据,然后创建一个新的 mysqli
对象来建立与数据库的连接。然后我们检查 connect_errno
的值,看看我们的数据库连接调用期间是否出现错误。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
建立连接后,我们运行第一个查询来查看是否已存在要更新其评分的电影的行。
如果没有这样的电影,我们运行另一个查询以将电影插入表中。由于这是该电影的第一次投票,因此我们将总票数设置为 1。
但是,如果表中已经有一行包含我们传递的 movie_id
,我们将从该行获取电影的总票数和当前平均评分。之后,我们计算新的评分并相应更新数据库。
最后,我们回显平均评分和总票数的新值以将其显示给用户。
最终想法
为了简单起见,这不是 100% 完整的解决方案。为了扩展这个项目,我们应该存储一个 cookie 以确保人们只投票一次,甚至记录 IP 地址。然而,这是一个很好的开始,并且非常适合跟踪对您网站上的博客文章、评论和图像等项目的投票。
The above is the detailed content of Build a 5-star rating system using jQuery, AJAX, and PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
