Like dislike rating system using jQuery, Ajax, PHP and MySQL

  •  
  •  
  •  
  •  
  •  
  •  

Like dislike rating system is quite useful for any website. Through this admin as well as webmasters can understand the users likes and dislikes. In this tutorial, I made a simple like dislike rating system using jQuery, Ajax, PHP, and MySQL. No page refreshing is required because I used jQuery and Ajax. Also, we store the data into the MySQL database using PHP and MySQL.

This like dislike rating system is designed such a way that users have to log in first to the website before doing like or dislike and each user can like or dislike each post several times but only one will be counted either one like or one dislike.

Like dislike rating system using jQuery, Ajax, PHP and MySQL

Before proceeding, have a look at the file structure–

  • index.php
  • mtb.js
  • update-choice.php
  • check-session.php
  • logout.php
  • logout.php

Database Tables

Create the following two tables in the database. Download the complete source code from the below link where you will get the sample data for these two tables. Instead of creating one extra table for storing like and dislike counts, I created two extra columns (likes and dislikes) in the post_list table which will store the ids of the logged in users. And the number of ids of each column is the number of likes and dislikes respectively.

CREATE TABLE `user_login` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `post_list` (
 `id` int(11) NOT NULL,
 `title` varchar(255) NOT NULL,
 `excerpt` varchar(255) NOT NULL,
 `image` varchar(255) NOT NULL,
 `link` varchar(255) NOT NULL,
 `likes` text NOT NULL,
 `dislikes` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

HTML & PHP – Display The Posts (index.php)

The below code fetches data from the database and displays the list of post.

<div class="container-fluid">
 		<div class="row">
 			<?php
 			$qry = "select * from `post_list`";
 			$res = mysqli_query($con, $qry);
 			if(mysqli_num_rows($res) > 0) {
 				while($row = mysqli_fetch_object($res)) {
 					$likes = array_filter(explode(',', $row->likes), function($value) { return $value !== ''; });
 					$dislikes = array_filter(explode(',', $row->dislikes), function($value) { return $value !== ''; });
 				?>
     			<div class="col-md-3">
     				<div class="mtb-post">
     					<form action="" method="post" id="<?php echo $row->id;?>">
     						<input type="hidden" name="post_id" id="post_id" value="<?php echo $row->id;?>">
       					<img class="img-fluid" src="images/<?php echo $row->image;?>">
       					<div class="post-info">
         					<div class="caption"><a href="<?php echo $row->link;?>" target="_blank"><h1><?php echo $row->title;?><h1></a></div>
         					<div class="excerpt"><?php echo $row->excerpt;?></div>
         					<div class="like-dislike">
         						<div class="like"><div class="counter"><?php echo sizeof($likes);?></div></div>
         						<div class="dislike"><div class="counter"><?php echo sizeof($dislikes);?></div></div>
         						<div class="clearfix"></div>
         					</div>
       					</div>
       					<div class="clearfix"></div>
     					</form>
     				</div>
     			</div>
 				<?php
 				}
 			}
 			?>
 		</div>
     </div>

jQuery and Ajax – Like Dislike Rating System (mtb.js)

Simple Ajax call which sends data to the update-choice.php and in returns get the number of likes and dislikes of any particular post.

$(document).ready(function() {
     $('.like, .dislike').click(function() {
     	var action = $(this).attr('class');
     	var post_id = $(this).parent().parent().parent().find("#post_id").val();
     	$.ajax({
     		url: 'check-session.php',
     		method: 'post',
     		success: function(data){
     			if(data != '') {
     				$.ajax({
     					url: 'update-choice.php',
     					method: 'post',
     					data:{action:action, post_id:post_id},
     					success: function(resp){
     						resp = $.trim(resp);
     						if(resp != '') {
     							resp = resp.split('|');
     							$('form#'+post_id+' .like .counter').html(resp[0]);
     							$('form#'+post_id+' .dislike .counter').html(resp[1]);
     						}
     					}
     				});
     			} else {
     				$('#popUpWindow').modal('show');
     			}
     		},
     	});
     });
});

PHP – Update Database (update.php)

The below PHP code updates and stores the user’s id in the likes or dislikes column based on the user’s choice in the database table.

<?php session_start(); ?>
<?php include('db.php');?>

<?php
if(isset($_POST) && !empty($_POST)) {
  $action = trim($_POST['action']);
  $post_id = trim($_POST['post_id']);

  if($action != "" && $post_id != "") {
    try {
      $qry = "select * from `post_list` where `id`=$post_id";
      $res = mysqli_query($con, $qry);
      if(mysqli_num_rows($res) == 1) {
        $row = mysqli_fetch_object($res);
        $likers = array_filter(explode(',', $row->likes), function($value) { return $value !== ''; });
        $dislikers = array_filter(explode(',', $row->dislikes), function($value) { return $value !== ''; });
        $like_count = count($likers);
        $dislike_count = count($dislikers);

        if($action == 'like') {
          if(!in_array($_SESSION['sess_user_id'], $likers)) {
            array_push($likers, $_SESSION['sess_user_id']);
            $like_count += 1;
          }

          $index = array_search(''.$_SESSION['sess_user_id'].'', $dislikers);
          if($index !== false) {
            unset($dislikers[$index]);
            $dislike_count -= 1;
          }
        } else if($action == 'dislike') {
          if(!in_array($_SESSION['sess_user_id'], $dislikers)) {
            array_push($dislikers, $_SESSION['sess_user_id']);
            $dislike_count += 1;
          }

          $index = array_search($_SESSION['sess_user_id'], $likers);
          if($index !== false) {
            unset($likers[$index]);
            $like_count -= 1;
          }					
        }


        $qry = "update `post_list` set `likes`='".implode(',', $likers)."', `dislikes`='".implode(',', $dislikers)."' where `id`=$post_id";
        mysqli_query($con, $qry);
        if(mysqli_affected_rows($con) == 1) {
          echo $like_count.'|'.$dislike_count;
        }
      }
    } catch (Exception $e) {
      echo "Error : " .$e->getMessage();
    }
  }
}
?>

Check Session  (check-session.php)

check-session.php returns the id of the user which is stored in the session after logging in. If it returns nothing then a login form will display for login to the website.

<?php 
  session_start(); 
  echo @$_SESSION['sess_user_id']; 
?>

Bootstrap Login Form –  (login.php)

<div class="container">       
       <div class="modal fade" id="popUpWindow">
         <div class="modal-dialog">
           <div class="modal-content">
             <!-- header -->
             <div class="modal-header">
               <button type="button" class="close" data-dismiss="modal">&times;</button>
               <h3 class="modal-title">Login Form</h3>
             </div>
             <!-- body -->
             <div class="modal-header">
               <form role="form" method="post" id="loginform">
                 <div class="form-group">
                   <input type="text" id="username" class="form-control" placeholder="Username" />
                   <input type="password" id="password" class="form-control" placeholder="Password" />
                 </div>
               </form>
             </div>
             <!-- footer -->
             <div class="modal-footer">
               <button type="submit" class="btn btn-primary btn-block login">Log In</button>
             </div>
             
           </div>
         </div>
       </div>
     </div>

Login with Ajax –  (mtb.js)

The below Ajax code is responsible for user validation using Ajax.

$('button.login').click(function() {
     	$.ajax({
     		url: 'login.php',
     		method: 'POST',
     		data: {username:$('#username').val(), password:$('#password').val()},
     		success: function(resp) {
     			resp = $.trim(resp);
     			alert(resp);
     			if(resp == "loggedin") {
     				$('#popUpWindow').modal('hide');
     				alert('You are logged in now.');
     			}
     		}
     	});
});

PHP –  User Validation (login.php)

The below PHP code checks if the user is valid or not based on the username and password.

<?php session_start(); ?>
<?php include('db.php');?>

<?php
$msg = ""; 
if(isset($_POST) && !empty($_POST)) {
  $username = trim($_POST['username']);
  $password = trim($_POST['password']);
  if($username != "" && $password != "") {
    try {
      $query = "select * from `user_login` where `username`='$username' and `password`='$password'";
      $res = mysqli_query($con, $query);
      if(mysqli_num_rows($res) == 1) {
        $row = mysqli_fetch_object($res);
        $_SESSION['sess_user_id']   = $row->id;
        $_SESSION['sess_username'] = $row->username;
        $_SESSION['sess_name'] = $row->name;
        echo 'loggedin';
      } else {
        echo "Invalid username and password!";
      }
    } catch (Exception $e) {
      echo "Error : ".$e->getMessage();
    }
  } else {
    $msg = "Both fields are required!";
  }
}
?>

Log Out – (logout.php)

Destroy the all sessions when users click on the logout link.

<?php
session_start();
session_destroy();
header("location: ./");
?>

Try the live demo on – like-dislike rating system using jQuery, Ajax, PHP and MySQL from the below Demo link. Also, you can download the complete source code from below Download link. Please like and share this tutorial with others.

About Mitrajit

5 comments on “Like dislike rating system using jQuery, Ajax, PHP and MySQL

  1. Dear About Mitrajit ..

    May I ask you something about the script mentioned above ? You are using myIsam based tables but all my databases are running on MariaDb Galera Clusters and myIsam is not really supported.

    Is it a problem when I convert the tables to InnoDb ? Thank you in advance!

  2. Hi i want to ask. Whe i use your source code and run it, the logout button still show when i click that. Please help me and reply it fast. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Prove you are a human *