Like social networking websites, we can see notification alerts on Facebook in the page header. This tutorial will add header notifications to notify the user about the latest data. This will be helpful to keep the user updated by notifying them what is new.
In this example, we have a notification icon in the page header. We show the notification count to represent how many new items are unread. On clicking the notification icon, we list the latest items.
This code shows an HTML form to post a new message to be notified to the user. After submitting this new message, it will be stored in a database with the ‘read’ status 0. The messages with the read status 0 are unread messages.
The sum of the unread messages is calculated and displayed near to the notification icon in the header.
<?php
$conn = new mysqli("localhost","root","","blog_samples");
$count=0;
if(!empty($_POST['add'])) {
$subject = mysqli_real_escape_string($conn,$_POST["subject"]);
$comment = mysqli_real_escape_string($conn,$_POST["comment"]);
$sql = "INSERT INTO comments (subject,comment) VALUES('" . $subject . "','" . $comment . "')";
mysqli_query($conn, $sql);
}
$sql2="SELECT * FROM comments WHERE status = 0";
$result=mysqli_query($conn, $sql2);
$count=mysqli_num_rows($result);
?>
<form name="frmNotification" id="frmNotification" action="" method="post" >
<div id="form-header" class="form-row">Add New Message</div>
<div class="form-row">
<div class="form-label">Subject:</div><div class="error" id="subject"></div>
<div class="form-element">
<input type="text" name="subject" id="subject" required>
</div>
</div>
<div class="form-row">
<div class="form-label">Comment:</div><div class="error" id="comment"></div>
<div class="form-element">
<textarea rows="4" cols="30" name="comment" id="comment"></textarea>
</div>
</div>
<div class="form-row">
<div class="form-element">
<input type="submit" name="add" id="btn-send" value="Submit">
</div>
</div>
</form>
We call a jQuery script on the click event of the notification icon. In this jQuery script, we call PHP via AJAX to get the latest messages from the database.
Clicking the notification icon removes the notification count from the header and lists all the latest data. The script is,
<script type="text/javascript">
function myFunction() {
$.ajax({
url: "view_notification.php",
type: "POST",
processData:false,
success: function(data){
$("#notification-count").remove();
$("#notification-latest").show();$("#notification-latest").html(data);
},
error: function(){}
});
}
$(document).ready(function() {
$('body').click(function(e){
if ( e.target.id != 'notification-icon'){
$("#notification-latest").hide();
}
});
});
</script>