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

ceri188

ceri188

ceri188 alternatif

ceri188

link ceri188

ceri188

RATU311

THOR311

THOR311

KUPU178

KUPU178

THOR311

THOR311

RATU311

RATU311

RATU311

RATU311

RATU311

Togel Online

KUPU178

Situs Togel

KUPU178

ceri188

ceri188

KUPU178

KUPU178

KUPU178

KUPU178

ceri188

ceri188

KUPU178

KUPU178

KUPU178

ratu311

ceri188

ceri188

ratu311

KUPU178

THOR311

ceri188

KUPU178

ceri188

THOR311

THOR311

RATU311

thor311 tajen bali

thor311 alternatif

situs toto4d

thor311 toto4d

thor311 akses

ceri188

KUPU178

daftar ceri188

cery188

ceri188

KUPU178

slot gacor

kupu 178

kupu178

ceri1888

ceri188

slot online

hoki311

togel online

ceri188

ding dong

ratu311

slot gacor

kupu178

live casino

kupu178

mix parlay

ceri188

judi bola online

thor311 slot

HOKI311

THOR311

RATU311

KUPU178

THOR311

THOR311

ceri188

ratu311

slot online

hoki311

kupu178

togel online

kupu178

slot gacor

ceri188

judi bola online

ceri188

ratu311

kupu178

RATU311

RATU311

live casino roullete

ceri188

slot pg soft

kupu178

KUPU178

THOR311

RATU311

KUPU178

KUPU178

THOR311

THOR311

THOR311

thor311 domino qq

thor311 akses

thor dingdong

ceri188

ceri188

KUPU178

kupu178

kupu178

togel

kupu178

mix parlay

ceri188

slot online

kupu178

THOR311

THOR311

KUPU178

KUPU178

kupu178

hoki311

togel online

kupu178

ceri188

ceri188

www.vrcorporate.in

phbalance.vn

togel hongkong

kupu178

slot gacor

kupu178

kupu178

ceri188

kupu178

KUPU178

RATU311

slot online

kupu178

THOR311

KUPU178

slot mahjong ways

hoki311

slot gacor

ceri188

kupu178

Casino Baccarat Online

kupu178

kupu178

ceri188

toto macau

KUPU178

Slot Gacor

KUPU178

RATU311

Mahjong ways

KUPU178

THOR311

RATU311

KUPU178

KUPU178

RATU311

RATU311

RATU311

Toto Togel

KUPU178

CERI188

Slot Sweet Bonanza 2500

KUPU178

RATU311

KUPU178 X SLOT777

judi bola online

THOR311

KUPU178 SLOT TERPERCAYA

KUPU178 TOGEL

TOTO 4D MACAU

KUPU178

KUPU178

THOR311

HOKI311

KUPU178

RATU311

Slot Mahjong Ways

KUPU178

CERI188

Slot Online Resmi

KUPU178

RATU311 SLOT ONLINE

KUPU178

KUPU178: Link Akses Resmi

KUPU178: Strategi Menang Di Game Live Casino

KUPU178

KUPU178: Minimal 200 Rupiah

THOR311

THOR311

THOR311

THOR311

THOR311

KUPU178

Slot Thailand

CERI188

CERI188

THOR311 RTP

RATU311

RATU311

CERI188

KUPU178 TOTO SLOT

CERI188 TOTO Singapore

THOR311

CERI188

RATU311: Alternatif karnpuracollege

Thor311 Terbaru

THOR311 MAHJONG

RATU311: BONUS SABUNG AYAM

CERI188: Masuk Akun Slot Super Cepat

THOR311

HOKI311

HOKI311

RATU311

HOKI311

KUPU178

RATU311

RATU311

THOR311

CERI188

CERI188

RATU311

RATU311

RATU311

Game Thor311

HOKI311

HOKI311

RATU311

HOKI311

HOKI311

THOR311

RATU311 NONTON BOLA

HOKI311 Link QRIS EWALLET

RATU311

HOKI311 Link Apk Resmi

CERI188

RATU311 judi bola

KUPU178

HOKI311

RATU311

THOR311

HOKI311

KUPU178

KUPU178

RATU311

RATU311

KUPU178

THOR311

KUPU178

RATU311

THOR311