Monday, 11 September 2017

PHP Like System with Notification using Ajax Jquery

If you are looking for PHP Ajax Web development tutorial on post or image like system with notification then you have come right place, here we have discuss small and simple like with notification by using PHP script with Ajax JQuery. In this system all user can share their post and all can like other user post. So, when one user has like other user post then post share user will received notification of particular post has been like by particular user. This type of feature we can mostly seen in social media sites in which all user has been engage with other users and all user has appriciate other users post by like his post.

Suppose you have use any social media sites, then you can find this type of things. For make this type of system we have use Core PHP script with Ajax JQuery. In this sytem user can login into system after login into system user can see all user post and with every post user can see number of likes of particular post and below post user can see like button also. So by clicking that like button any user can like any user post.






Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing2", "root", "");
session_start();
?>


function.php



<?php
//function.php

function is_user_has_already_like_content($connect, $user_id, $content_id)
{
 $query = "
 SELECT * FROM user_content_like 
 WHERE content_id = :content_id
 AND user_id = :user_id
 ";
 $statement = $connect->prepare($query);

 $statement->execute(
  array(
   ':content_id' =>  $content_id,
   ':user_id'  =>  $user_id
  )
 );
 $total_rows = $statement->rowCount();
 if($total_rows > 0)
 {
  return true;
 }
 else
 {
  return false;
 }

}

function count_content_like($connect, $content_id)
{
 $query = "
 SELECT * FROM user_content_like 
 WHERE content_id = :content_id
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':content_id'  => $content_id
  )
 );
 $total_rows = $statement->rowCount();
 return $total_rows;
}

?>


index.php



<?php
//index.php
include('database_connection.php');
if(!isset($_SESSION["user_id"]))
{
 header("location:login.php");
}
?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Like System with Notification using Ajax Jquery</title>
  <script src="js/jquery.min.js"></script>
  <link rel="stylesheet" href="css/bootstrap.min.css" />
  <script src="js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">PHP Like System with Notification using Ajax Jquery</h2>
   <br />
   <div align="right">
    <a href="logout.php">Logout</a>
   </div>
   <br />
   <nav class="navbar navbar-inverse">
      <div class="container-fluid">
        <div class="navbar-header">
           <a class="navbar-brand" href="#">Webslesson - <?php echo $_SESSION['user_name']; ?></a>
        </div>
        <ul class="nav navbar-nav navbar-right">
           <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="label label-pill label-danger count"></span> Notification</a>
            <ul class="dropdown-menu"></ul>
           </li>
        </ul>
      </div>
   </nav>
   <br />
   <br />
   <form method="post" id="form_wall">
    <textarea name="content" id="content" class="form-control" placeholder="Share any thing what's in your mind"></textarea>
    <br />
    <div align="right">
     <input type="submit" name="submit" id="submit" class="btn btn-primary btn-sm" value="Post" />
    </div>
   </form>
   
   <br />
   <br />
   
   
   <br />
   <br />
   <h4>Latest Post</h4>
   <br />
   <div id="website_stuff"></div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 load_stuff();

 function load_stuff()
 {
  $.ajax({
   url:"load_stuff.php",
   method:"POST",
   success:function(data)
   {
    $('#website_stuff').html(data);
   }
  })
 } 
 $('#form_wall').on('submit', function(event){
  event.preventDefault();
  if($.trim($('#content').val()).length == 0)
  {
   alert("Please Write Something");
   return false;
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'done')
     {
      $('#form_wall')[0].reset();
      load_stuff();
     }
    }
   })
  }
 });

 $(document).on('click', '.like_button', function(){
  var content_id = $(this).data('content_id');
  $(this).attr('disabled', 'disabled');
  $.ajax({
   url:"like.php",
   method:"POST",
   data:{content_id:content_id},
   success:function(data)
   {
    if(data == 'done')
    {
     load_stuff();
    }
   }
  })
 });

 load_unseen_notification();

 function load_unseen_notification(view = '')
 {
  $.ajax({
   url:"load_notification.php",
   method:"POST",
   data:{view:view},
   dataType:"json",
   success:function(data)
   {
    $('.dropdown-menu').html(data.notification);
    if(data.unseen_notification > 0)
    {
     $('.count').html(data.unseen_notification);
    }
   }
  })
 }
 $(document).on('click', '.dropdown-toggle', function(){
  $('.count').html('');
  load_unseen_notification('yes');
 });
});
 
</script>


insert.php



<?php
//insert.php

include('database_connection.php');

if(isset($_POST["content"]))
{
 $query = "
 INSERT INTO content 
 (user_id, description) 
 VALUES(:user_id, :description)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   'user_id'  => $_SESSION['user_id'],
   'description' => $_POST["content"]
  )
 );
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'done';
 }
}

?>


like.php



<?php
//like.php
include('database_connection.php');

if(isset($_POST["content_id"]))
{
 $query = "
 INSERT INTO user_content_like (content_id, user_id) 
  VALUES(:content_id, :user_id)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
    ':content_id' => $_POST["content_id"],
    ':user_id'  => $_SESSION["user_id"]
   )
 );
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'done';
 }
}

?>


load_notification.php



<?php
//load_notification.php
include('database_connection.php');
if(isset($_POST["view"]))
{
 $query = "
 SELECT user_content_like.user_id, content.description, user_details.user_name, user_details.user_image FROM user_content_like
 INNER JOIN content 
  ON content.content_id = user_content_like.content_id 
 INNER JOIN user_details 
  ON user_details.user_id = user_content_like.user_id 
  WHERE content.user_id = :user_id 
  AND user_content_like.status = :status 
  ORDER BY user_content_like.user_content_like_id DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
    ':user_id'  => $_SESSION['user_id'],
    ':status'  => 'not-seen'
   )
 );
 $result = $statement->fetchAll();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  foreach($result as $row)
  {
   $user_name = '';
   if($row['user_id'] == $_SESSION['user_id'])
   {
    $user_name = '<img src="images/'.$row["user_image"].'" class="img-thumbnail" width="40" height="40" /> You have';
   }
   else
   {
    $user_name = '<img src="images/'.$row["user_image"].'" class="img-thumbnail" width="40" height="40" /> '.$row['user_name'].' has ';
   }
   $output .= '
   <li>
     <a href="#">
      <strong>'.$user_name.'</strong> like your post "'.substr($row["description"], 0, 25).'"
     </a>
    </li>
   ';
  }
 }
 else
 {
  $output .= '
  <li><a href="#" class="text-bold text-italic">No Notification Found</a></li>
  ';
 }
 if($_POST["view"] != '')
 {
  $select_query = "
  SELECT * FROM content WHERE user_id = :user_id
  ";
  $statement = $connect->prepare($select_query);
  $statement->execute(
   array(
     ':user_id' => $_SESSION['user_id']
    )
  );
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $update_query = "
   UPDATE user_content_like 
    SET status = 'seen' 
    WHERE content_id = :content_id 
    AND status = :status
   ";
   $statement = $connect->prepare($update_query);
   $statement->execute(
    array(
      ':content_id'  => $row['content_id'],
      ':status'  => 'not-seen'
     )
   );
  }
 }
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
    ':user_id'  => $_SESSION['user_id'],
    ':status'  => 'not-seen'
   )
 );
 $total_row = $statement->rowCount();
 $data = array(
   'notification'   => $output,
   'unseen_notification' => $total_row
  );
 echo json_encode($data);
}


?>


load_stuff.php



<?php
//load_stuff.php

include('database_connection.php');
include('function.php');

if(isset($_SESSION["user_id"]))
{
 $output = '';
 $query = "
 SELECT content.content_id, content.user_id, content.description, user_details.user_name, user_details.user_image FROM content 
 INNER JOIN user_details 
 ON user_details.user_id = content.user_id
 ORDER BY content_id DESC
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $total_rows = $statement->rowCount();
 if($total_rows > 0)
 {
  foreach($result as $row)
  {
   $like_button = '';
   if(!is_user_has_already_like_content($connect, $_SESSION["user_id"], $row["content_id"]))
   {
    $like_button = '
    <button type="button" name="like_button" class="btn btn-info btn-xs like_button" data-content_id="'.$row["content_id"].'">Like</button>
    ';
   }
   $count_like = count_content_like($connect, $row["content_id"]);
   $output .= '
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title"><img src="images/'.$row["user_image"].'" class="img-thumbnail" width="40" height="40" /> By '.$row["user_name"].'
      <button type="button" name="total_like" id="total_like" class="btn btn-warning btn-xs">'.$count_like.' Like</button>
     </h3>
    </div>
    <div class="panel-body">
     '.$row["description"].'
    </div>
    <div class="panel-footer" align="right">
     '.$like_button.'
    </div>
   </div>
   ';
  }
 }
 else
 {
  $output = 'Nobody has share nothing';
 }
 echo $output;
}

?>


login.php



<?php
//login.php

include("database_connection.php");

$message = '';

if(isset($_POST["login"]))
{
 if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
 {
  $message = '<label>Both Fields are required</label>';
 }
 else
 {
  $query = "
  SELECT * FROM user_details 
  WHERE user_email = :user_email
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    'user_email' => $_POST["user_email"]
   )
  );
  $count = $statement->rowCount();
  if($count > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if(password_verify($_POST["user_password"], $row["user_password"]))
    {
     $_SESSION['user_id'] = $row['user_id'];
     $_SESSION['user_name'] = $row['user_name'];
     header("location:index.php");
    }
    else
    {
     $message = '<label>Wrong Password</label>';
    }
   }
  }
  else
  {
   $message = '<label>Wrong Email Address</labe>';
  }
 }
}



?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Like System with Notification using Ajax Jquery</title>
  <script src="js/jquery.min.js"></script>
  <link rel="stylesheet" href="css/bootstrap.min.css" />
  <script src="js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">PHP Like System with Notification using Ajax Jquery</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">Login</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>User Email</label>
       <input type="text" name="user_email" id="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" id="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="login" id="login" class="btn btn-info" value="Login" />
      </div>
     </form>

    </div>
   </div>
   <br />
   <p><strong>Password</strong> - password</p>
  </div>
 </body>
</html>


logout.php



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


Database



--
-- Database: `testing2`
--

-- --------------------------------------------------------

--
-- Table structure for table `content`
--

CREATE TABLE IF NOT EXISTS `content` (
  `content_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `description` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `content`
--

INSERT INTO `content` (`content_id`, `user_id`, `description`) VALUES
(1, 2, 'Apple Phone is a best phone ever.'),
(2, 2, 'Google is most visited site all over the world.'),
(3, 1, 'Google is world biggest Internet company.'),
(7, 1, 'Google''s New Street View Cameras Will Help Algorithms Index The Real World'),
(9, 2, 'Youtube new look is very nice for any user');

-- --------------------------------------------------------

--
-- Table structure for table `user_content_like`
--

CREATE TABLE IF NOT EXISTS `user_content_like` (
  `user_content_like_id` int(11) NOT NULL,
  `content_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `status` enum('not-seen','seen') NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_content_like`
--

INSERT INTO `user_content_like` (`user_content_like_id`, `content_id`, `user_id`, `status`) VALUES
(1, 1, 3, 'seen'),
(2, 2, 3, 'seen'),
(3, 2, 4, 'seen'),
(4, 1, 4, 'seen'),
(5, 1, 2, 'seen'),
(6, 2, 2, 'seen'),
(7, 1, 6, 'seen'),
(8, 1, 5, 'seen'),
(9, 2, 5, 'seen'),
(10, 2, 6, 'seen'),
(11, 2, 1, 'seen'),
(12, 1, 1, 'seen'),
(13, 3, 2, 'seen'),
(14, 3, 1, 'seen'),
(15, 4, 1, 'seen'),
(16, 4, 2, 'seen'),
(17, 5, 2, 'seen'),
(18, 8, 1, 'not-seen'),
(19, 7, 1, 'seen'),
(20, 7, 2, 'seen'),
(21, 9, 1, 'seen'),
(22, 9, 2, 'seen');

-- --------------------------------------------------------

--
-- Table structure for table `user_details`
--

CREATE TABLE IF NOT EXISTS `user_details` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(200) NOT NULL,
  `user_password` varchar(200) NOT NULL,
  `user_name` varchar(200) NOT NULL,
  `user_type` enum('master','user') NOT NULL,
  `user_image` varchar(150) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_details`
--

INSERT INTO `user_details` (`user_id`, `user_email`, `user_password`, `user_name`, `user_type`, `user_image`) VALUES
(1, 'john_smith@gmail.com', '$2y$10$cHpf3TzonURXDENRiRF0de1ycSfnM4NJ27sdwyUCf5L.sewDlkCBe', 'John Smith', 'master', 'john_smith.jpg'),
(2, 'dona_huber@gmail.com', '$2y$10$lcLYyNeK1adgzYcBplv45uuXHFuFyWYThnj3nB2SZ/LbQvtWSoGjO', 'Dona Huber', 'user', 'dona_huber.jpg'),
(3, 'roy_hise@gmail.com', '$2y$10$XlyVI9an5B6rHW3SS9vQpesJssKJxzMQYPbSaR7dnpWjDI5fpxJSS', 'Roy Hise', 'user', 'roy_hise.jpg'),
(4, 'peter_goad@gmail.com', '$2y$10$n1B.FdHNwufTkmzp/pNqc.EiwjB8quQ1tBCEC7nkaldI5pS.et04e', 'Peter Goad', 'user', 'peter_goad.jpg'),
(5, 'sarah_thomas@gmail.com', '$2y$10$s57SErOPlgkIZf1lxzlX3.hMt8LSSKaYig5rusxghDm7LW8RtQc/W', 'Sarah Thomas', 'user', 'sarah_thomas.jpg'),
(6, 'edna_william@gmail.com', '$2y$10$mfMXnH.TCmg5tlYRhqjxu.ILly8s9.qsLKOpyxgUl6h1fZt6x/B5C', 'Edna William', 'user', 'edna_william.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `content`
--
ALTER TABLE `content`
  ADD PRIMARY KEY (`content_id`);

--
-- Indexes for table `user_content_like`
--
ALTER TABLE `user_content_like`
  ADD PRIMARY KEY (`user_content_like_id`);

--
-- Indexes for table `user_details`
--
ALTER TABLE `user_details`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `content`
--
ALTER TABLE `content`
  MODIFY `content_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `user_content_like`
--
ALTER TABLE `user_content_like`
  MODIFY `user_content_like_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT for table `user_details`
--
ALTER TABLE `user_details`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

0 comments:

Post a Comment