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:
- Database Structure
- Get Events from Database
- Preparing Events to be Displayed
- 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:
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
$servername = "localhost";
$username = "root";
$password = " ";
$dbname="remorobodb";
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
B. Fetch Data
$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:
$resultCount = count($result);
for ($i=0;$i < $resultCount ;$i++)
{
$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;
}
B. Prepare to Print
This source code prepares:
- Final Level: This is the final Maximum Level found to color the bell by that color, (gray, orange, red, ...)
- Total Count of Notifications which is not dismissed.
- Notifications Array: All information for every Notification data like details, subject, time,....
Hint: Code in attached and gitHub is better format.
$output = '';
$finalLevel=-2;
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
);
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:
- Take the ID For the Notification to Dismiss.
- All parameter (optional) You can send (
ALL
) as Parameter which means will dismiss all notifications at once.
$id =$_GET[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");
}
Front End
The following code is to load the unseen events in a context menu, and total number, bell color. Using Ajax.
var data;
var currentNotificationIndex;
var currentNotificationId;
function load_unseen_notification(view = '')
{
var serverFile = "./remoroboinclude/ajax/notification.php?id="+view;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
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;
}
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" ;
}
}
}
xmlhttp.open("GET",serverFile,true);
xmlhttp.send(null);
}
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
< div class="modal fade" id="divmessageModel" role="dialog">
< div class="modal-dialog">
<!--
< div class="modal-content">
< div class="modal-header" id="divmessageheadercontainer">
< button type="button" class="close"
data-dismiss="modal">×</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">
<!--
< label>< input type="checkbox" value="ALL"
id="divmssagesDismissAllCheckBox" value="">
Dismiss All</label>
<!--
< 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><!--
<!--
< ! -- 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