Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Web Notification Icon with Simple PHP

3.00/5 (3 votes)
21 Jan 2019CPOL3 min read 32.8K   659  
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

License

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