Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / PHP

Web Notification Icon with Simple PHP

Rate me:
Please Sign up or sign in to vote.
3.00/5 (3 votes)
20 Jan 2019CPOL3 min read 31.7K   650   5   8
Dynamic Notification Icon with Colors and dismiss with Ajax live Update

Image 1

Introduction

In the web development environment (Dynamic Website), we care about the backend and events happened and need to notify the user about it using dynamic way without bothering him or even forcing him to refresh the page to get the last updated events. In this article, I will tell you how to create a notification dynamic bell to notify you dynamically about events happened while browsing your web page.

Background

Lately, I developed a Robotics Application (RemoRobo) with HTML front end and PHP backend, to control Arduino and RaspberryPi, I needed some technique to update the browser for the events with its source and level,... etc, I detached this part from the project to make it useful for the world so you can use it in your projects.

Using the Code

The source code is divided into two main parts as usual, Front End, and Back End.

Back End

In the Backend side, we have the following operations:

  1. Database Structure
  2. Get Events from Database
  3. Preparing Events to be Displayed
  4. Dismiss Events

1. DatabaseStructure

I used MySql database because it is free and most PHP applications use it, but you can use any Database engine you like. Here is the database notification table structure example:

Image 2

Notification Table has the following columns:

Name Type Description
id int (Primary key) It is used to get the events and notifications to the front end
Subject text (Must) One or two words to describe the event or notification
Source int (optional) You can Identify the event or notification source by numbers like 1= USER , 2- Server 3- Hardware,...etc.
Details String (optional) One line of details about the Event.
date Time/Date (Must) Time the event happened, it is used for filter and sort events what to show first.
dismiss tinyInt (Must) This is a Flag (0 and 1), (Zero) The Event Not seen, which means it will appear in the notification list and number in the bell label.
(One) Means the Event seen and dismissed by the user, so it is just saved on the Database for future use but it will not appear in the notification list anymore.
Level tinyInt (Must) This is the level of the Event ,1 = critical, 2= Warning , 3 = Information. you can add more if you like but you should add code for coloring it as well.
Also, we use this as optional Sort factor, means you can sort the notification according to occurrence time or level value.

2. Get Events from Database

To get data from database, we should use the following PHP code:

A. Connection

PHP
	//PHP code 
		< ?php
$servername = "localhost";
$username = "root";
$password = " ";
$dbname="remorobodb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//echo "Connected successfully";
		?>

B. Fetch Data

PHP
$select_query = "SELECT * FROM `notification` WHERE `dismiss` = 0    
_ORDER BY `notification`.`date` DESC";
 $result = mysqli_query($conn, $select_query);

3. Preparing Events to be Displayed

A. Convert to Array

Now, we will re-organize the returned data to be displayed on the screen, by adding it into Arrays, we have two Arrays:

  • arrayItem: This array contains the Item values like: ID, subject, and convert it into useful names
  • resultArray: This array contains all the result Items after organizing.

Example:

PHP
$resultCount =  count($result);
for ($i=0;$i < $resultCount ;$i++)
{
//$arrayItem["index"]=$i; // FOR Indexing result 
$arrayItem["notification_id"] = $result[$i][0];
$arrayItem["notification_subject"] = $result[$i][1];
$arrayItem["notification_source"] = $result[$i][2];
$arrayItem["notification_text"] = $result[$i][3];
$arrayItem["notification_date"] = $result[$i][4];
$arrayItem["notification_dismiss"] = $result[$i][5];  
$arrayItem["notification_level"] = $result[$i][6];
$arrayItem["fulldetails"] = $result[$i][7];
$resultArray[$i] = $arrayItem; // Add the current result item to the total result array.
}

B. Prepare to Print

This source code prepares:

  1. Final Level: This is the final Maximum Level found to color the bell by that color, (gray, orange, red, ...)
  2. Total Count of Notifications which is not dismissed.
  3. Notifications Array: All information for every Notification data like details, subject, time,....

Image 3

Hint: Code in attached and gitHub is better format.

PHP
$output = '';
$finalLevel=-2;
//////////// Rendering the lresult //////////////////
//$resultCount = count($resultArray);
if ($resultCount >0)
{
    $finalLevel= $resultArray[0]["notification_level"];

    for($i=0;$i< $resultCount;$i++)
    {
        if ($resultArray[$i]["notification_level"] < $finalLevel) 
        {
            $finalLevel = $resultArray[$i]["notification_level"];
        }
        $bgColor = getBGColor( $resultArray[$i]["notification_level"]);
        $resultArray[$i]["bgColor"] = $bgColor;
      $output .= '
   < li>
   < a href="#" onclick="showModal('.$resultArray[$i]["notification_id"].',
     '.$i.',\''.$resultArray[$i]["notification_subject"].'\',\'Hi there \')")>
   < div style="background :'.$bgColor.';" >
   < strong >'.$resultArray[$i]["notification_subject"].'</strong>
   </div>
   <small><em>'.$resultArray[$i]["notification_text"].'</em></small>   
   </a>
   </li>
   ';
    }
}
else{
     $output .= '
     < li>< a href="#" class="text-bold text-italic">No Noti Found</a></li>';
}
$bgColor= getBGColor($finalLevel);
$data = array(
    'bellColor'=>$bgColor,
     'unseen_notification'  => $resultCount,
    'notification' => $output,

    'result'=>$resultArray
    
);
///////////////////Display the Result///////////////
echo json_encode($data);
function getBGColor($level)
{
    $bgColor = '';
    switch($level)
    {
        case 1:
                $bgColor="red";
                break;
        case 2:
                 $bgColor="orange";
                break;
         case 3:
                $bgColor="gray";                
                break;
    }
    return $bgColor;  
}

4. Dismiss Events

Dismiss Notification is the operation of converting dismiss field from 0 to 1.

This source code:

  1. Take the ID For the Notification to Dismiss.
  2. All parameter (optional) You can send (ALL) as Parameter which means will dismiss all notifications at once.
PHP
$id =$_GET[id];
//echo $id;
if ($id=='All')
{
   dismiss(); 
}
else
{
    dismiss(' where id = '.$id);
}
function dismiss($options)
{   
   $sql = "Update `notification` SET `dismiss` = 1 ".$options;
DB_query($sql);
    
echo ($sql." Excecuted");
 //echo "done";
}

Front End

The following code is to load the unseen events in a context menu, and total number, bell color. Using Ajax.

PHP
	 ///////Global Variables 
	 
	    var data; // notification Data json
   var currentNotificationIndex; //current notification message 
var currentNotificationId; //Current Notification Id
 
	 
		 function load_unseen_notification(view = '')
 {
var serverFile = "./remoroboinclude/ajax/notification.php?id="+view;
     
 if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.ontimeout= load_unseen_notificationTimeOut;
     xmlhttp.onerror = load_unseen_notificationError;
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
     data = JSON.parse(this.responseText);   
    if(data.unseen_notification > 0)
    { 
      document.getElementById("dropdown-menu").innerHTML =  data.notification;        
        document.getElementById("count").innerHTML = data.unseen_notification;
        document.getElementById("bellIcon").style.color = data.bellColor;
        document.getElementById("count").style.color = data.bellColor;        
        //addLog("notification Updated");
   }
        else
        {
document.getElementById("dropdown-menu").innerHTML = 
"< li>< strong>Welcome </ strong><br /><small>
< em>No new Notification ... </ em></ small></ li> ";
             document.getElementById("count").innerHTML="";
        document.getElementById("bellIcon").style.color = "transparent" ;
            
        }
    }//for onreadystatechange Function on success 
  } //for onreadystatechange Event  state change 
  
  xmlhttp.open("GET",serverFile,true);
  xmlhttp.send(null);   
}
        // Events Handellings ...
       function load_unseen_notificationTimeOut()
        {            
           alert("The request for unseen Messages timed out.");
        }
        
         function load_unseen_notificationError(){
    alert("Error");
        }
    </script>

The code in PHP to see the details already written in the preparation to print except the function: Show modal which we will show here:

  • showModal: JavaScript with HTML to show Notification details in bootstrap modal

Image 4

HTML
	 < div class="modal fade" id="divmessageModel" role="dialog">
    < div class="modal-dialog">
    
      <!-- Modal content-->
      < div class="modal-content">
        < div class="modal-header" id="divmessageheadercontainer">
           < button type="button" class="close" 
           data-dismiss="modal">&times;</button>
          < h4 class="modal-title" id="divmodalheader">Modal Header</h4>
        < / div>
          < div id ="divmodalmessageid" style=" visibility: hidden;"></div>
        < div class="modal-body" id ="divmodalbody">
          < p>Some text in the modal.</p>
        < /div>
        < div class="modal-footer">
            
    <!--<div class="checkbox"> -->
  < label>< input type="checkbox" value="ALL"  
  id="divmssagesDismissAllCheckBox" value="">
    Dismiss All</label>
<!-- </div> -->
          < button type="button" class="btn btn-default" 
          onclick="dismiss(currentNotificationId)">Dismiss</button>
          < button type="button" class="btn btn-default" 
          data-dismiss="modal">Close</button>
        < /div>
      < /div>
      
    < /div>
  < /div><!-- end message Modal-->
    <!--Modal JS-->
    < ! --  script  -- >///////////////// Script
        function showModal(id='',index='',title="Hello title", 
        body= " this is the body ")
    {
        var fullTitle='';  
        var fullBody='';
        if (id>0 && id != null)
        { 
           //fullTitle +=id;            
        }
        fullTitle +=title;
        document.getElementById("divmssagesDismissAllCheckBox").checked = false;
        document.getElementById("divmodalheader").innerHTML=fullTitle;
       /*
       $arrayItem["notification_id"] = $result[$i][0];
$arrayItem["notification_subject"] = $result[$i][1];
$arrayItem["notification_source"] = $result[$i][2];
$arrayItem["notification_text"] = $result[$i][3];
$arrayItem["notification_date"] = $result[$i][4];
$arrayItem["notification_dismiss"] = $result[$i][5];  
$arrayItem["notification_level"] = $result[$i][6];
$arrayItem["fulldetails"] = $result[$i][7];

       */
         fullBody  +="<label> Full details  :</label>"+ "" + "<br/>";
        
        fullBody  +="<label>Source:</label>"+  
        data.result[index]["notification_source"] + "<br/>";
         
         fullBody  +="<label>message:</label>"+  
         data.result[index]["notification_text"] + "<br/>";
         
          fullBody  +="<label>details:</label>"+  
          data.result[index]["fulldetails"] + "<br/>";
          fullBody  +="<label>date:</label>"+  
          data.result[index]["notification_date"] + "<br/>";
        
          fullBody  +="<label>id:</label>"+  
          data.result[index]["notification_id"] + "<br/>";        
        
 document.getElementById("divmessageheadercontainer").style.backgroundColor = 
                         data.result[index]["bgColor"];
        document.getElementById("divmodalbody").innerHTML= fullBody;        
       
        currentNotificationIndex = index;
        currentNotificationId = id;        
        
        $('#divmessageModel').modal("show");       
    }  
function dismiss (id='')
        {
            $('#divmessageModel').modal("hide");
            var dismissServerFile = "./remoroboinclude/db/dismiss.php?id=";
            if (id!= null)
                {
                    if (id==''|| document.getElementById
                    ("divmssagesDismissAllCheckBox").checked == true)
                        {
                           addLog("dismiss All Notifications");
                            dismissServerFile+="All";
 document.getElementById("count").innerHTML ="";
                        }
                else{
                 addLog("Dismiss with Id "+id);
                    dismissServerFile+=id;
                    document.getElementById("count").innerHTML ="..";
                    
                    //load_unseen_notification();
                    } 
                    RunPhp(dismissServerFile,'','','','notification');
                    
                    } // for id != null            
        }
    < ! -- end modal js-->

RunPhp

RunPhp function is generic Ajax function, I wrote about it in this article: Simple Dynamic JavaScript Ajax Function

History

Updates and latest version of code can be found on gitHub.

Website: http://www.ArabicRobotics.com

This article was originally posted at https://github.com/ArabicRobotics/webNotificationIcon

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader ArabicRobotics.com
Egypt Egypt
Tareq Gamal El-din Mohammed,
---------
Website:
www.ArabicRobotics.com

---------

Graduated from Modern Academy for Computer science and Information Technology. Egypt,
Then flow Microsoft development track Certificates:
MCAD.NET (Microsoft Certified Application Developer)
MCSD.NET (Microsoft Certified Solution Developer)
Microsoft SharePoint Administration, Configuration and Development.

Robotics fields was a Hobby since 2002,
started to develop some applications for "Robosapien", "RoboSapienV2", "RS Media", RoboMe and WowWee Rovio. from WowWee company,

Started working with robots as a professional way at 2014
By using "NAOqi" Robotics from Aldebaran.

By developing some applications and libraries like :
NAO.NET.
https://www.youtube.com/watch?v=oOyy-2XyT-c

OpenCV with NAO Robot:

- NAORobot Vision using OpenCV -TotaRobot P1
https://www.youtube.com/watch?v=MUcj8463x08

- NAO Robot Vision using OpenCV - P2
https://www.youtube.com/watch?v=93k1usaS-QM

NAO Alarm Clock :
https://www.youtube.com/watch?v=djLlMeGLqOU
-----------------------------

also Robotic Arm Project:


Other Projects Developed by Tareq Gamal El-din Mohammed :

Developed and posted some applications in Code Project web site like :

- Control your Distributed Application using Windows and Web Service
http://www.codeproject.com/Articles/101895/Control-your-Distributed-Application-using-Windows


- Quick and dirty directory copy
http://www.codeproject.com/Articles/12745/Quick-and-dirty-directory-copy

- Program Execute Timer(From the Web)
http://www.codeproject.com/Articles/12743/Program-Executer-Timer

Comments and Discussions

 
SuggestionCan be done easier with jQuery Pin
Mick du Gland17-Jan-19 22:24
Mick du Gland17-Jan-19 22:24 
include jQuery and use this timer function

JavaScript
var refreshTime = 60000; // every 1 minutes in milliseconds
window.setInterval( function() {
    $.ajax({
        type: "POST",
        url: "_checkNotifications.php",
        success: function(returnData) {
          // console.log('refreshed: '+data);
          $('#message').html($('#message').html() + returnData);
        }
    });
}, refreshTime );


1. set the refreshTime to whatever you need in your project
2. create
_checkNotifications.php
which should check your table on new notifications and return that data.
PHP
$sqlid = mysqli_connect($host, $user, $psw, $dbname);

$sql   = "SELECT * FROM notification
          WHERE dismiss = 0";
$res   = mysqli_query($sqlid, $sql);
$msg   = "";
while ($row = mysqli_fetch_object($res)) {
	$msg .= $row->subject . ": " . $row->details . " (" . $row->date . ")<br />";
	$sqlu = "UPDATE notification SET dismiss = 1 WHERE id = " . $row->id;
	mysqli_query($sqlid, $sqlu);
}
echo $msg;

GeneralRe: Can be done easier with jQuery Pin
Tareq_Gamal18-Jan-19 4:01
Tareq_Gamal18-Jan-19 4:01 
QuestionCant reproduce on my ambient Pin
Member 1412003116-Jan-19 4:40
Member 1412003116-Jan-19 4:40 
AnswerRe: Cant reproduce on my ambient Pin
Tareq_Gamal16-Jan-19 17:49
Tareq_Gamal16-Jan-19 17:49 
AnswerRe: Cant reproduce on my ambient Pin
Tareq_Gamal16-Jan-19 19:10
Tareq_Gamal16-Jan-19 19:10 
AnswerRe: Cant reproduce on my ambient Pin
Member 1412003117-Jan-19 2:20
Member 1412003117-Jan-19 2:20 
GeneralRe: Cant reproduce on my ambient Pin
Tareq_Gamal17-Jan-19 23:06
Tareq_Gamal17-Jan-19 23:06 
GeneralRe: Cant reproduce on my ambient Pin
Tareq_Gamal18-Jan-19 3:54
Tareq_Gamal18-Jan-19 3:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.