Monday, 27 February 2017

Facebook Style Header Notification using PHP Ajax Bootstrap



If you are looking for web tutorial on How to make Facebook like Header Notification in PHP by using Ajax JQuery with Bootstrap. In Facebook we can see any type of Notification alert has been view on page Header. So We have make Facebook style Notification Popup using PHP Script with Ajax Jquery Bootstrap. By using this feature we can display latest alert on page header automatically and user will be notify by latest alert.

In this post we have display notification on page header. First of all notification means what are the activity done in our system and notify that activity to user. So user can be updated regarding what activity has been happens in the system. So PHP Notification alert when new record is inserted into system and then after user will be notify by notification count has been appear on page header. So when user has been seen notification alert then count has been remove from the page header that means user has been seen that notification. So this is very helpful feature in any web application and user will be updated with new data. Here we have make simple PHP Notification system like Facebook.

Now lets start discussing on How to make Facebook like Notification dropdown by using PHP Ajax JQuery with Bootstrap Framework.




Database




--
-- Database: `testing`
--

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

--
-- Table structure for table `comments`
--

CREATE TABLE IF NOT EXISTS `comments` (
  `comment_id` int(11) NOT NULL,
  `comment_subject` varchar(250) NOT NULL,
  `comment_text` text NOT NULL,
  `comment_status` int(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `comments`
--
ALTER TABLE `comments`
  ADD PRIMARY KEY (`comment_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
  MODIFY `comment_id` int(11) NOT NULL AUTO_INCREMENT;

This comments table with four column like comment_id, comment_subject, comment_text and comment_status. In comment_status column we have integer data type and so when new record inserted then in this column it will insert zero, here zero means it is unread and when we will see notification then this will be updated to one, that means this records has been read by user.

index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Facebook Style Header Notification using PHP Ajax Bootstrap</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="#">Webslesson Tutorial</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" style="border-radius:10px;"></span> <span class="glyphicon glyphicon-envelope" style="font-size:18px;"></span></a>
       <ul class="dropdown-menu"></ul>
      </li>
     </ul>
    </div>
   </nav>
   <br />
   <h2 align="center">Facebook Style Header Notification using PHP Ajax Bootstrap</h2>
   <br />
   <form method="post" id="comment_form">
    <div class="form-group">
     <label>Enter Subject</label>
     <input type="text" name="subject" id="subject" class="form-control">
    </div>
    <div class="form-group">
     <label>Enter Comment</label>
     <textarea name="comment" id="comment" class="form-control" rows="5"></textarea>
    </div>
    <div class="form-group">
     <input type="submit" name="post" id="post" class="btn btn-info" value="Post" />
    </div>
   </form>
   
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 function load_unseen_notification(view = '')
 {
  $.ajax({
   url:"fetch.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);
    }
   }
  });
 }
 
 load_unseen_notification();
 
 $('#comment_form').on('submit', function(event){
  event.preventDefault();
  if($('#subject').val() != '' && $('#comment').val() != '')
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     $('#comment_form')[0].reset();
     load_unseen_notification();
    }
   });
  }
  else
  {
   alert("Both Fields are Required");
  }
 });
 
 $(document).on('click', '.dropdown-toggle', function(){
  $('.count').html('');
  load_unseen_notification('yes');
 });
 
 setInterval(function(){ 
  load_unseen_notification();; 
 }, 5000);
 
});
</script>


This is our index page and on this page we have use Jquery and Bootstrap Framework. On this page we have make one Header by using Bootstrap CSS Library.

For display Notification in dropdown format, we have use Bootstrap dropdown class. By using this class we will display unread notification in dropdown format.

Under header for display figure of unread notification we have define into span tag with class count. In this tag we have display unread notification figure. In this post for get Notification we have make one simple form for create notification. So when this form has been submitted then new notification has been created and display on header.

For load notification on page load, so we have make on jquery function load_unseen_notification(), when page has been loaded this function will be called and it will display notification on page header. In this function we add one view argument with blank value. So When this function has been called without argument, then this function will only fetch notification from Mysql table but when when this function has been called with any view argument value then this function will fetch notification from table and it will update all unread notification column like comment_status to zero to one. That means all notification has been read by user.

Then after we have write jquery code for submit form data to myql table. When form has been submitted then new notification has been created so for display that notification we have called load_unseen_notification() function under Ajax request.

Now when we have click on notification icon then number of notification label has been remove from header. So we have write jquery code on dropdown-toggle class on click event. Here when user click on for see notification, so here we have first clear count class in which we have display notification number by using html method with blank value. And for change the status of notification from unread to read, we have called load_unseen_notification() function with argument view is equal to yes, that means this function will not only fetch notification data but also it will also update comment_status column value to zero to one.

For get automatic notification on web page without refreshing page, so we want to called load_unseen_notification() function on regular time interval. So we have use setInterval() method with five thousand milisecond. This method will be called load_unseen_notification() function on every five second. And it will display notification on web page.



fetch.php



<?php
//fetch.php;
if(isset($_POST["view"]))
{
 include("connect.php");
 if($_POST["view"] != '')
 {
  $update_query = "UPDATE comments SET comment_status=1 WHERE comment_status=0";
  mysqli_query($connect, $update_query);
 }
 $query = "SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5";
 $result = mysqli_query($connect, $query);
 $output = '';
 
 if(mysqli_num_rows($result) > 0)
 {
  while($row = mysqli_fetch_array($result))
  {
   $output .= '
   <li>
    <a href="#">
     <strong>'.$row["comment_subject"].'</strong><br />
     <small><em>'.$row["comment_text"].'</em></small>
    </a>
   </li>
   <li class="divider"></li>
   ';
  }
 }
 else
 {
  $output .= '<li><a href="#" class="text-bold text-italic">No Notification Found</a></li>';
 }
 
 $query_1 = "SELECT * FROM comments WHERE comment_status=0";
 $result_1 = mysqli_query($connect, $query_1);
 $count = mysqli_num_rows($result_1);
 $data = array(
  'notification'   => $output,
  'unseen_notification' => $count
 );
 echo json_encode($data);
}
?>


This page has been received request from load_unseen_notification() function. If this page received function with value of argument then it will also update value of column_status column value from 0 to 1. Here zero means unread notification and 1 means read notification. After this function has been fetch last five notification data from table and send to function. In this function it will also count total of unread notification also.

insert.php



<?php
//insert.php
if(isset($_POST["subject"]))
{
 include("connect.php");
 $subject = mysqli_real_escape_string($connect, $_POST["subject"]);
 $comment = mysqli_real_escape_string($connect, $_POST["comment"]);
 $query = "
 INSERT INTO comments(comment_subject, comment_text)
 VALUES ('$subject', '$comment')
 ";
 mysqli_query($connect, $query);
}
?>


This page has been called when form data has been submitted then this function first clean form field data and it will insert into comment table.

connect.php



<?php 
//connect.php;
$connect = mysqli_connect("localhost", "root", "", "testing");
?>


This page is use for making database connection and we have use this page in all page by using include() statement

So We hope you have understand this topic Facebook Like Live Notification by using PHP Script with Ajax JQuery with Bootstrap. If you have any query regarding this web tutorial, please comment your query in comment box. If you like this tutorial please share with your friends or even you can also share on social media also.

74 comments:

  1. Very nice will definitely try out.

    ReplyDelete
  2. Muito bom... obrigado por compartilhar!

    ReplyDelete
  3. Thanks for this please keep making more

    ReplyDelete
  4. hi, i tried your tutorial and the php script seems to work but i'm having trouble in populating the json data in to the dropdown menu. i have tweaked it to suit my code need your advice.

    ReplyDelete
  5. Nice Tutorial help me Alot Thanks.

    ReplyDelete
  6. How to separate post comment with notification page.
    nb:
    Post comment is in admin and notification page exist in user

    ReplyDelete
  7. How to separate post comment with notification page
    nb:
    Post comment is in admin and notification page exist in user

    ReplyDelete
  8. Thanks for your nice tutorial ... Highly appreciated
    But I got the following error:
    Uncaught ReferenceError script.js 1244
    defaultResponsiveData is not defined

    ReplyDelete
  9. there is an issue if a user view notification then notification will be read for all users..
    there must be a coockies and last notification view implementation

    ReplyDelete
  10. Hi , Thanks for this great tutorial. I am one your big fans. i have downloaded some of your videos , subscribed to your YouTube channel and regularly visits your weblessons blog.
    Please i need clarification on how to position the notification on my website.
    the notification is supposed to appear on the header part of the user dashboard as they login. The form that submits data is in another page, how do i make the notification appear on the dashboard since your example happens on the same page? And what process do i need to follow to identify specific user as they login so they can see notifications peculiar to them.
    Thanks in advance great teacher.

    ReplyDelete
  11. Fantastic work sir keep going like this and enlighten our skills

    ReplyDelete
  12. Hello !! hey, how can add a sound when is a new notification available thanks for the time if you are reading

    ReplyDelete
  13. Code link in the video is not compatible with database DDL script you put here
    Too much differences between column names(comment_subject, sub) and table name as well (comments, comment)

    ReplyDelete
  14. in my project, i am including header on another user's page. what all changes do i have to make ?

    ReplyDelete
  15. the script is not inserting the form data and its not showing anything on the notification bar

    ReplyDelete
  16. This code is not working. It is not showing me any results.Can you please give me your mail id so that i can send you the code.

    ReplyDelete
  17. i want top change dropdown in a modal box

    ReplyDelete
  18. its awesome but how create notifcations when membership is expiring and we have to notfiy the admin before the expiry date

    ReplyDelete
  19. the notification alert does not appear on the web page.
    please help

    ReplyDelete
  20. HOLY ***! THIS IS ONE OF THE BEST TUTORIALS I'VE EVER FOUND, considering that I only find "concepts" suggested by devs.

    ReplyDelete
  21. thank you from
    Nasport air handling - sudan

    ReplyDelete
  22. thanks for your tutorial amazing

    ReplyDelete
  23. I have done to like your instruction. But It can not work

    ReplyDelete
  24. If i want to select one notofication and get all its content displayed in another page.how can i do it??

    ReplyDelete
  25. We can use the above bootstrap in our project ????

    ReplyDelete
  26. very very useful thank you so much

    ReplyDelete
  27. awesome post very helpfull

    ReplyDelete
  28. thanks, please am a beginner i'll like to have the source code
    sent to my email. Thanks very much, it's awesome

    ReplyDelete
  29. i can't set charset UTF8 font ?????? you help edit problem i don't because function or fetch.php " thank you for help "

    ReplyDelete
  30. Excellent work. Everything is working fine except the badge with 0 or 1 is not displaying. comment_status is showing NULL. Value is not changing from zero to one. Please help

    ReplyDelete
  31. i need something realted to this but my que is that i am taking input type="time" form user and when the time matches to the current tym user should get notification in website .how's it possible to do please help !!!!!

    ReplyDelete
  32. Noce work, but can you make it to be clicked instead of seen

    ReplyDelete
  33. Please how can I create notification with replay using php and Ajax

    ReplyDelete
  34. Sir please I've tried working on this but its not displaying with ajax but if i remove ajax it works fine

    ReplyDelete
  35. not working please help.

    ReplyDelete
  36. how add sound when notif appear? like sound wav or mp3 or ogg

    ReplyDelete
  37. can you do it in codeigniter

    ReplyDelete
  38. Can you do it on codeigniter

    ReplyDelete