pippo
pippo

Reputation: 183

Notification system jQuery, PHP, and MySQL

I'm trying to develop a notification system using jQuery and PHP. So I've created a new table in the database where I'm going to store all the new notifications. Using jQuery I've been able to show an alert (bubble icon) showing the number of new lines added to the database, but I'm now stuck because I don't really know how to update the database (fire update.php file) when I click the icon (.icon-bell) which does activate a drop-down menu.

This is the jQuery script I've added to the index page

<script type="text/javascript">
    $(document).ready(function(){
        $("#datacount").load("select.php");
        setInterval(function(){
            $("#datacount").load('select.php')
        }, 20000);
    });
</script>

This is the HTML code in the index page

<li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
        <i class="icon-bell">
        </i>
        <span class="badge badge-success"><div id="datacount">
            </div>
        </span>
    </a>
    <ul class="dropdown-menu" >
        <li class="external">
            <h3>
                <span class="bold">12 pending</span>
                notifications
            </h3>
            <a href="page_user_profile_1.html">view all</a>
        </li>
        <li>
            <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
                <li>
                    <a href="javascript:;">
                        <span class="time">just now</span>
                        <span class="details">
                            <span class="label label-sm label-icon label-success">
                                <i class="fa fa-plus">
                                </i>
                            </span> New user registered. </span>
                    </a>
                </li>
            </ul>
        </li>
    </ul>
</li>

This is the select.php file

<?php
$sql = "SELECT * from tbl_noti where status = 'unread'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>

This is the update.php file

<?php
$sql = "update tbl_noti set status = 'read'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>

Upvotes: 2

Views: 19393

Answers (3)

Shahroze Nawaz
Shahroze Nawaz

Reputation: 589

You can use PHP + Ajax to accomplish this task. I have created a simple notification system and you can easily clone it from GitHub(https://github.com/shahroznawaz/php-notifications).

let's create an index.php file and put the following code. it will create a form. all the data will get by ajax call and updated in the view.

<!DOCTYPE html>

<html>

<head>

 <title>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="#">PHP Notification 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-bell" style="font-size:18px;"></span></a>

      <ul class="dropdown-menu"></ul>

     </li>

    </ul>

   </div>

  </nav>

  <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> 

Now create ajax calls like this:

<script>

$(document).ready(function(){

// updating the view with notifications using ajax

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();

// submit form and get new records

$('#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");
 }

});

// load new notifications

$(document).on('click', '.dropdown-toggle', function(){

 $('.count').html('');

 load_unseen_notification('yes');

});

setInterval(function(){

 load_unseen_notification();;

}, 5000);

});

</script>

You also need to fetch all the records from database and update the status for the notification viewd. create fetch.php file and add the following code:

<?php

include('connect.php');

if(isset($_POST['view'])){

// $con = mysqli_connect("localhost", "root", "", "notif");

if($_POST["view"] != '')

{
   $update_query = "UPDATE comments SET comment_status = 1 WHERE comment_status=0";
   mysqli_query($con, $update_query);
}

$query = "SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5";
$result = mysqli_query($con, $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>

  ';
}
}

else{
    $output .= '<li><a href="#" class="text-bold text-italic">No Noti Found</a></li>';
}

$status_query = "SELECT * FROM comments WHERE comment_status=0";
$result_query = mysqli_query($con, $status_query);
$count = mysqli_num_rows($result_query);

$data = array(
   'notification' => $output,
   'unseen_notification'  => $count
);

echo json_encode($data);
}
?>

Now you will be able to see the notification in navigation bar like this:

enter image description here

when you click the dropdown the status of views notification will update and count will disappear.

enter image description here

Upvotes: 7

Neville
Neville

Reputation: 528

Use ajax to execute the PHP queries so they can execute in real time without page reload.

Upvotes: -1

bnahin
bnahin

Reputation: 816

To execute PHP asynchronously, you need to use AJAX. jQuery has a few functions for this purpose.

$.ajax: Fully customizable asynchronous request, including error handling, headers, etc.

$.post: AJAX restricted to POST.

$.get: AJAX restricted to GET.

Both $.post and $.get can be accomplished with $.ajax, however they are, in most situations, easier to work with. You most likely will only need $.get in this case, since no additional data is being passed in the request.

Example code:

$.get(
  "update.php",
  function(result) {
    console.log(result)
  }
);

Here, result is the data outputted from update.php.

Upvotes: 0

Related Questions