PHP notification alert when a new record is inserted using AJAX


PHP notification alert when a new record is inserted using AJAX

Hi friends, in this tutorial we will learn how to send a PHP notification alert when a new record is inserted using ajax and jquery. This is almost similar to Facebook-like notifications.

PHP notification alert when a new record is inserted using AJAX
PHP notification alert when a new record is inserted using AJAX
PHP notification alert when a new record is inserted using AJAX

As we all know notification is a very essential part of any type of web-based application or any dynamic website. To do so, you have to follow the below-given steps one by one.

Also read, How to Get Only Date from Timestamp in PHP

Required steps of PHP notification alert

Step 1:- Create a table in the database.

DDL information of the table

CREATE TABLE `notifications` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `subject` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `comment` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `status` int(10) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Step 2:- In this step, we will create a PHP file using an HTML form with two fields such as subject and comment, and save the file name as phpnotification.php.

phpnotification.php

<html>
<head>
<title>Notification System</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<style>
.container{
	width:40%;
	height:30%;
	padding:20px;
	margin-top: 5%;
}
</style>
</head>

<body>
	<div class="container">
		<nav class="navbar navbar-inverse">
			   <div class="container-fluid">
				    <div class="navbar-header">
				     <a class="navbar-brand" style="color: white;">Pending Notification</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:20px;color: white;"></span></a>
				      <ul class="dropdown-menu"></ul>
				     </li>
				    </ul>
			   </div>
		  </nav>
		<br />
		<div id="show_notification"></div>
		<form method="post" action="#">
			   <div id="error_div"></div>
			   <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 Message</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" />-->
			    <button type="button" class="btn btn-primary" name="post" id="post">Save</button>
			   </div>
		</form>
    </div>
</body>
</html>

Step 3:- In this step, we will send the form values with the help of the AJAX request i.e. without reloading the page using the done() function as shown below

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
	$('#post').click(function(){
		//alert('ok');
		var subject = $('#subject').val();
		var comment = $('#comment').val();
		if(subject=='' || comment==''){

		   $('#error_div').html('<div class="alert alert-danger"><strong>Please enter the required fields.</strong></div>');
		}
		else{
			 $.ajax({

			  url:"phpnotification.php",
			  method:"POST",
			  data:{'subject':subject,'comment':comment,'post':1},
			  dataType:"html"
			  
			 })
			 .done(function(data){
		    	
		    	load_unseen_notification();
		        $('#show_notification').html('<div class="alert alert-success alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a><strong>Success!</strong>Notifications inserted successfully.</div>');
		    	$('#subject').val('');
		    	$('#comment').val('');
		    	$('#error_div').html('');
 
		     })
		    .fail(function(xhr,textStatus,errorThrown,data)
				{
				
				alert(errorThrown);
				
				});
		}

	});
});
</script>

Step 4:- In this step, we will receive the form values from the AJAX request and store them in the table of our database where the information will be stored.

Here, we will not create any separate PHP file for storing the data because we are using the same file for storing the form values with the help of PHP scripts as shown below.

Also, note that we are using a status field so that we can populate the unseen notifications after submitting the data depending on that status.

<?php
$servername='localhost';
$username="root";
$password="";
try
{
	$con=new PDO("mysql:host=$servername;dbname=blog",$username,$password);
	$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	//echo 'connected';
}
catch(PDOException $e)
{
	echo '<br>'.$e->getMessage();
}
if(isset($_POST["post"]))
{

   $subject=$_POST['subject'];
   $comment=$_POST['comment'];
   $status = 0;
	
	$sql="INSERT INTO notifications(subject,comment,status)VALUES('$subject','$comment','$status')";
	$stmt=$con->prepare($sql);
	$stmt->execute();
	
	
}

Step 5:- In this step, we are going to view the unseen notification in the dropdown menu after clicking the bell icon as shown in the HTML form.

Here, we have used the click() function with dropdown menu class and another function called load_unseen_notification() to call the notification information which is not seen yet as shown below.

$(document).on('click', '.dropdown-toggle', function(){
		 $('.count').html('');
		 load_unseen_notification('yes');
		});
		setInterval(function(){
		 load_unseen_notification();
		}, 5000);
function load_unseen_notification(view = '')
		{
		 $.ajax({
		  url:"fetchnotification.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();

Step 6:- In this step, we will create a separate PHP file called fetchnotification.php which is used to collect the unseen notifications from the database and return the response back to the AJAX request sent from the function load_unseen_notification() as shown below.

fetchnotification.php:-

<?php
$servername='localhost';
$username="root";
$password="";
try
{
	$con=new PDO("mysql:host=$servername;dbname=blog",$username,$password);
	$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	//echo 'connected';
}
catch(PDOException $e)
{
	echo '<br>'.$e->getMessage();
}
if(isset($_POST['view'])){

	if($_POST["view"] != '')
	{
	   $stmt=$con->prepare("update notifications set status = 1 where status = 0");
	   $stmt->execute();
	}
	//Fetching the rows from database
	$stmt1=$con->prepare("SELECT * FROM notifications ORDER BY id DESC LIMIT 5");
	$stmt1->execute();

$output = '';
	if($stmt1->rowCount() > 0)
	{
	while($row = $stmt1->fetch(PDO::FETCH_ASSOC))
	{
	  $output .= '
	  <li>
	  <a href="#">
	  <strong>'.$row["subject"].'</strong><br />
	  <small><em>'.$row["comment"].'</em></small>
	  </a>
	  </li>
	  ';
	}
	}
	else{
	    $output .= '<li><a href="#" class="text-bold text-italic">No Notification Found</a></li>';
	}
	$stmt2=$con->prepare("SELECT * FROM notifications WHERE status = 0");
	$stmt2->execute();
	$count = $stmt2->rowCount();
	$data = array(
	   'notification' => $output,
	   'unseen_notification'  => $count
	);
	echo json_encode($data);
	}
?>

Complete Code:-

<?php
$servername='localhost';
$username="root";
$password="";
try
{
	$con=new PDO("mysql:host=$servername;dbname=blog",$username,$password);
	$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	//echo 'connected';
}
catch(PDOException $e)
{
	echo '<br>'.$e->getMessage();
}
if(isset($_POST["post"]))
{

   $subject=$_POST['subject'];
   $comment=$_POST['comment'];
   $status = 0;
	
	$sql="INSERT INTO notifications(subject,comment,status)VALUES('$subject','$comment','$status')";
	$stmt=$con->prepare($sql);
	$stmt->execute();
	
	
}

?>
<html>
<head>
<title>Notification System</title>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 
<style>
.container{
	width:40%;
	height:30%;
	padding:20px;
	margin-top: 5%;
}
</style>
</head>

<body>
	<div class="container">
		<nav class="navbar navbar-inverse">
			   <div class="container-fluid">
				    <div class="navbar-header">
				     <a class="navbar-brand" style="color: white;">Pending Notification</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:20px;color: white;"></span></a>
				      <ul class="dropdown-menu"></ul>
				     </li>
				    </ul>
			   </div>
		  </nav>
		<br />
		<div id="show_notification"></div>
		<form method="post" action="#">
			   <div id="error_div"></div>
			   <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 Message</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" />-->
			    <button type="button" class="btn btn-primary" name="post" id="post">Save</button>
			   </div>
		</form>
    </div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
	$('#post').click(function(){
		//alert('ok');
		var subject = $('#subject').val();
		var comment = $('#comment').val();
		if(subject=='' || comment==''){

		   $('#error_div').html('<div class="alert alert-danger"><strong>Please enter the required fields.</strong></div>');
		}
		else{
			 $.ajax({

			  url:"phpnotification.php",
			  method:"POST",
			  data:{'subject':subject,'comment':comment,'post':1},
			  dataType:"html"
			  
			 })
			 .done(function(data){
		    	
		    	load_unseen_notification();
		        $('#show_notification').html('<div class="alert alert-success alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a><strong>Success!</strong>Notifications inserted successfully.</div>');
		    	$('#subject').val('');
		    	$('#comment').val('');
		    	$('#error_div').html('');
 
		     })
		    .fail(function(xhr,textStatus,errorThrown,data)
				{
				
				alert(errorThrown);
				
				});
		}

	});
});
	function load_unseen_notification(view = '')
		{
		 $.ajax({
		  url:"fetchnotification.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();
	$(document).on('click', '.dropdown-toggle', function(){
		 $('.count').html('');
		 load_unseen_notification('yes');
		});
		setInterval(function(){
		 load_unseen_notification();
		}, 5000);

</script>
</script>

</body>
</html>

Conclusion: I hope this tutorial will help you to understand the PHP notification system. If there is any doubt then please leave a comment below.


Leave a Comment

APK KUPU178

KUPU178

CERI188

CERI188

RATU311

KUPU178

THOR311 DOMINO QQ

judi bola online

Mix Parlay

CERI188

CERI188

CERI188

KUPU178

RATU311

live casino online

RATU311

Mix Parlay

Sabung Ayam Online

Slot PG Soft

CERI188

RATU311

RATU311

RATU311

THOR311

RATU311

RATU311

CERI188

THOR311

CERI188

THOR311

RATU311

RATU311

THOR311

THOR311

Game Thor311

THOR311

HOKI311

live casino

sv388

HOKI311

HOKI311

slot mahjong

Thor311 Alternatif

RATU311

HOKI311

HOKI311

HOKI311

HOKI311

CERI188

THOR311 RESMI

THOR311 AKSES

THOR311

THOR311 RTP

RATU311

RATU311

THOR311

parlay

HOKI311

RATU311

RATU311

THOR311

Ceri188

Thor311 Game Online

Thor311 Aplikasi

LINK CERI188

RATU311 NONTON BOLA

RATU311

CERI188 Link RTP LIVE

THOR311

Thor311 Live Casino

CERI188

akses VIP THOR311

THOR311

link daftar THOR311

THOR311

situs thor311

THOR311 LOGIN

THOR311

THOR311

RATU311

RATU311

HOKI311 Link SABUNG AYAM RESMI

HOKI311 Link QRIS EWALLET

RATU311

LINK CERI188

parlay

HOKI311 Link RTP Gacor

THOR311

RATU311

THOR311

HOKI311 Link Apk Resmi

RATU311

KUPU178

RATU311

RATU311

RATU311

CERI188

CERI188 Situs Spaceman Terbaik 2026

KUPU178 Link Daftar

CERI188

CERI188

CERI188

CERI188

CERI188

HOKI311

THOR311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

CERI188 Live Casino

HOKI311 Lapak Arena Slot

RATU311 judi bola

CERI188 Live Casino

HOKI311 Link Spaceman Online

RATU311

HOKI311 Link Daftar Resmi

CERI188 Toto SGP Online

KUPU178

KUPU178

KUPU178

KUPU178

HOKI311 TEMBAK IKAN ONLINE

RATU311

CERI188 PANDUAN MAXWIN SLOT ONLINE

RATU311

RATU311

KUPU178

HOKI311 Link Login Alternatif

HOKI311 Live Casino Online

HOKI311 Situs Slot Gacor

THOR311

THOR311

situs judi bola

Ceri188 Game Online

CERI188

link login CERI188

link login CERI188

CERI188

link login CERI188

link login CERI188

link daftar CERI188

THOR311

HOKI311

HOKI311

CERI188

CERI188

CERI188

parlay

THOR311

RATU311

RATU311

HOKI311

HOKI311

parlay

HOKI311

RATU311

THOR311

KUPU178

HOKI311

KUPU178

KUPU178

KUPU178

HOKI311

parlay

slot gacor

kupu178 link alternatif

kupu178 slot

kupu178 daftar

kupu178 login

link daftar kupu178

judi bola

HOKI311

RATU311

link alternatif RATU311

Link daftar RATU311

link login RATU311

RATU311

RATU311

RATU311

RATU311

KUPU178

KUPU178

KUPU178

THOR311

KUPU178

KUPU178

KUPU178

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

RATU311

THOR311

RATU311

KUPU178

KUPU178

HOKI311

THOR311

KUPU178

THOR311

THOR311

slot thailand

judi bola

THOR311

THOR311

KUPU178

THOR311

situs bola

THOR311

slot gacor

slot gacor

yakuza303

slot gacor

unobet77

slot gacor

slot gacor

RATU311

parlay

parlay

slot gacor

mix parlay

judi bola

judi bola

mix parlay

parlay

judi bola

sv388

judi bola

judi bola

judi bola

parlay

THOR311