How To Make Web Push Notifications in PHP, JQuery , AJAX And Mysql

Web Push Notifications not only useful for displaying the latest blog post to increase your website traffic, but you can apply them to information systems / web base CRUD applications. Since the smartphone era, browsers such as Chrome and Firefox has started massive changes against the product to make it more user-friendly and responsive. Firefox browser has equipped with push notification since version 44 and chrome on version 42.

How To Make Web Push Notifications In PHP, JQuery , AJAX And Mysql

The application of push notification script on a web page can be various, such as:

  • The notification to display the stock runs out.
  • Chat Notification If your system there is a chat feature.
  • A notification if there is a new mail.
  • Notification for stock movement.

And much more. I think the Web Push Notifications is a requirement but not required to be applied.

Keep in mind the Web Push Notifications are not always useful. Often users are annoyed with a notification that is useless and annoying their performance.

Okay, as an example we will create a web push notification where a user does a broadcast message to another user with many options. The criteria as follows:

  1. Notification may appear several times according to schedule
  2. The user can define the interval the next notification will come out.
  3. The system will check the notification every 30 seconds
  4. A notification will be closed after 8 seconds.

See my video footage of how the application works

Lets start the tutorial How to make web push notifications in PHP, JQuery , AJAX And Mysql

1. Create a new database with the name “notifikasi“.

Create Database Mysql Notifikasi For Web Push Notification Data

2. Create 2 table with name user and notif like the following image :

Create Tabel User Web Push Notification By Seegatesite.com.png

Create Tabel Notif Web Push Notification By Seegatesite.com

or please execute the following SQL code

DROP TABLE IF EXISTS `notif`;

CREATE TABLE `notif` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `notif_msg` text,
  `notif_time` datetime DEFAULT NULL,
  `notif_repeat` int(11) DEFAULT '1' COMMENT 'schedule in minute',
  `notif_loop` int(11) DEFAULT '1',
  `publish_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `username` varchar(13) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

/*Data for the table `notif` */

insert  into `notif`(`id`,`notif_msg`,`notif_time`,`notif_repeat`,`notif_loop`,`publish_date`,`username`) values (1,'hello, this is sample web push notification, you will redirect to seegatesite.com after click this notify','2017-02-08 08:48:54',1,0,'2017-02-08 08:47:54','ronaldo');
insert  into `notif`(`id`,`notif_msg`,`notif_time`,`notif_repeat`,`notif_loop`,`publish_date`,`username`) values (2,'hello, this is sample web push notification, you will redirect to seegatesite.com after click this notify','2017-02-08 09:17:11',1,2,'2017-02-08 09:16:11','donald');

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

/*Data for the table `user` */

insert  into `user`(`username`,`password`) values ('admin','123');
insert  into `user`(`username`,`password`) values ('donald','123');
insert  into `user`(`username`,`password`) values ('ronaldo','123');
insert  into `user`(`username`,`password`) values ('messi','123');

3.Create a new project folder as “notification

4. Creates 8 PHP file PHP dan 1 js file like the following :

  • ajax.php : used to hold files to be executed by jquery ajax.
  • broadcast.php : used to create notification message.
  • dbconn.php : a class who used to create a MySQL connection with PDO
  • sql.php: a class who used to keep MySQL query syntax.
  • index.php : index or dashboard page.
  • isLogin.php : to checking if user is login or not.
  • login.php : login page
  • logout.php : logout code
  • mynotif.js : Javascript code who will execute the notification message

Create a login page

Copy the code below and save in login.php

<?php SESSION_START(); if(isset($_SESSION['username'])) { header('Location: index.php'); } include "dbconn.php"; include "sql.php"; $sql = new sql(); $user = $sql->listUser();
?>
<!DOCTYPE html>
<html>
<head>
	<title>Login</title>
</head>
<body>
	
<h2>Login Application</h2>


<form method="post"  action="<?php echo $_SERVER['PHP_SELF']; ?>
">
		
<table>
			
<tr>
				
<td>Username</td>


<td><input type="text" name="username"></td>

			</tr>


<tr>
				
<td>Password</td>


<td><input type="password" name="pass"></td>

			</tr>


<tr>
				
<td colspan=2>
<hr>
</td>

			</tr>


<tr>
				
<td><button type="submit" name="submit">Login</button></td>

			</tr>

		</table>

	</form>

	<?php if(isset($_POST['submit'])){ if(isset($_POST['username']) and isset($_POST['pass'])) { /*check login*/ $check = $sql->getLogin($_POST['username'],$_POST['pass']);
			if($check[2] == 1)
			{
				$_SESSION['username'] = $_POST['username'];
				header('Location: index.php');
			}else
			{
				echo '* username or password not valid';
			}
		}
	}
	?>
	
<h2>How To Make Web Push Notifications in PHP, JQuery , AJAX And Mysql</h2>


<h3>http://seegatesite.com</h3>


<h4>admin user : admin , password : 123</h4>


<h5>user : ronaldo , password : 123</h5>


<h5>user : donald , password : 123</h5>


</body>
</html>

Create logout script.

Copy the code below and save at logout.php

<?php SESSION_START(); unset($_SESSION['username']); header('Location: login.php'); ?>

Create MySQL Connection With PDO

Copy the code below and save in dbconn.php file

<?php class dbconn { public $dblocal; public function __construct() { } public function initDBO() { $this->dblocal = new PDO("mysql:host=localhost;dbname=notifikasi;charset=latin1","root","123456",array(PDO::ATTR_PERSISTENT => true));
		$this->dblocal->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);	
		
	}
}
?>

Create class sql query syntax on the sql.php file

Copy the following code and save in sql.php

<?php class sql extends dbconn { public function __construct() { $this->initDBO();
	}
	public function saveNotif($msg,$time,$loop,$loop_every,$user){
		$db = $this->dblocal;
		try
		{
			$stmt = $db->prepare("insert into notif(notif_msg, notif_time, notif_repeat, notif_loop,username) values(:msg , :bctime , :repeat , :loop,:user) ");

			$stmt->bindParam("msg", $msg);
			$stmt->bindParam("bctime", $time);
			$stmt->bindParam("loop", $loop);
			$stmt->bindParam("repeat", $loop_every);
			$stmt->bindParam("user", $user);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = 'sukses';
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex->getMessage();
			return $stat;
		}
	}
	public function updateNotif($id,$nextime)
	{
		$db = $this->dblocal;
		try
		{
			$stmt = $db->prepare("update notif set notif_time = :nextime, publish_date=CURRENT_TIMESTAMP(), notif_loop = notif_loop-1 where id=:id ");
			$stmt->bindParam("id", $id);
			$stmt->bindParam("nextime", $nextime);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = 'sukses';
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex->getMessage();
			return $stat;
		}
	}
	
	public function listNotifUser($user){
		$db = $this->dblocal;
		try
		{
			$stmt = $db->prepare("SELECT * FROM notif
				WHERE username= :user
				AND notif_loop > 0
				AND notif_time <= CURRENT_TIMESTAMP()"); $stmt->bindParam("user", $user);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			$stat[2] = $stmt->rowCount();
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex->getMessage();
			return $stat;
		}
	}
	public function getLogin($user,$pass){
		$db = $this->dblocal;
		try
		{
			$stmt = $db->prepare("select * from user where username = :user and password = :pass");
			$stmt->bindParam("user", $user);
			$stmt->bindParam("pass", $pass);
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			$stat[2] = $stmt->rowCount();
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex->getMessage();
			return $stat;
		}
	}
	
	public function listUser(){
		$db = $this->dblocal;
		try
		{
			$stmt = $db->prepare("select * from user");
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			$stat[2] = $stmt->rowCount();
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex->getMessage();
			return $stat;
		}
	}
	public function listNotif(){
		$db = $this->dblocal;
		try
		{
			$stmt = $db->prepare("select * from notif");
			$stmt->execute();
			$stat[0] = true;
			$stat[1] = $stmt->fetchAll(PDO::FETCH_ASSOC);
			$stat[2] = $stmt->rowCount();
			return $stat;
		}
		catch(PDOException $ex)
		{
			$stat[0] = false;
			$stat[1] = $ex->getMessage();
			return $stat;
		}
	}
}

Create PHP function to check user login

Copy the following code and save it in a file isLogin.php

<?php if(!isset($_SESSION['username'])) { header('Location: login.php'); } ?>

Creating a page for adding a list of notifications

Copy the following code and save the file broadcast.php

<?php SESSION_START(); include "isLogin.php"; include "dbconn.php"; include "sql.php"; $sql = new sql(); $user = $sql->listUser();
?>
<!DOCTYPE html>
<html>
<head>
	<title>Broadcast Menu</title>
</head>
<body>
	
<h2>Simple Broadcast Message Menu</h2>

	<a href="index.php">Home</a> |	<a href="logout.php">Logout</a>
	
<hr>


<form method="post"  action="<?php echo $_SERVER['PHP_SELF']; ?>
">
		
<table>
			
<tr>
				
<td>Message</td>


<td><textarea name="msg" cols="50" rows="4"></textarea></td>

			</tr>


<tr>
				
<td>Broadcast time</td>


<td><select name="time"><option>Now</option></select>	</td>

			</tr>


<tr>
				
<td>Loop</td>


<td><select name="loops">
					<?php 
					for ($i=1; $i<=5 ; $i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
						<?php } ?>
				</select> time</td>

			</tr>


<tr>
				
<td>Loop Every</td>


<td><select name="loop_every">
					<?php 
					for ($i=1; $i<=60 ; $i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
						<?php } ?>
				</select> Minute</td>

			</tr>


<tr>
				
<td>For</td>


<td><select name="user">
					<?php foreach ($user[1] as $key) { ?>
<option value="<?php echo $key['username'] ?>"><?php echo $key['username'] ?></option>
						<?php } ?>
				</select></td>

			</tr>


<tr>
<td colspan=2>
<hr>
</td>
</tr>


<tr>
				
<td><button name="submit" type="submit">Broadcast </button></td>

			</tr>

		</table>

	</form>

	<?php if (isset($_POST['submit'])) { if(isset($_POST['msg']) and isset($_POST['time']) and isset($_POST['loops']) and isset($_POST['loop_every']) and isset($_POST['user'])) { $msg = $_POST['msg']; $time = date('Y-m-d H:i:s'); $loop= $_POST['loops']; $loop_every=$_POST['loop_every']; $user = $_POST['user']; /*save Notification*/ $save = $sql->saveNotif($msg,$time,$loop,$loop_every,$user);
			if($save[0] == true)
			{
				echo '* save new notification success';
			}else{
				echo 'error save data : '.$save[1];
			}

		}else{
			echo '* completed the parameter above';
		}
	}	
	?>
	
	
<table border=1>
		
<thead>

<tr>
				
<td>No</td>


<td>Next Schedule</td>


<td>Message</td>


<td>Remains</td>


<td>User</td>

			</tr>

		</thead>


<tbody>
			<?php $a =1; $list = $sql->listNotif();
			foreach ($list[1] as $key) {
				?>
				
<tr>
					
<td><?php echo $a ?></td>


<td><?php echo $key['notif_time'] ?></td>


<td><?php echo $key['notif_msg'] ?></td>


<td><?php echo $key['notif_loop']; ?></td>


<td><?php echo $key['username'] ?></td>

				</tr>

				<?php $a++; } ?>
		</tbody>

	</table>

</body>
</html>

Explanation :

I will be a little bit of explaining some of the parameters used:

  • message : The content of the message.
  • broadcast time : time the message was sent.
  • loop : the number of messages to be sent
  • loop every : The time lag sending the first message to the next message
  • for : To whom this message is addressed

Create Index or Dashboard Page

Copy the following code and save it in a file index.php

<?php SESSION_START(); include "isLogin.php"; include "dbconn.php"; include "sql.php"; $sql = new sql(); $user = $sql->listUser();
?>
<!DOCTYPE html>
<html>
<head>
	<title>test web browser notifikasi</title>
</head>
<body>
	
<h2>Dashboard </h2>

	<?php if($_SESSION['username'] == 'admin') { ?>
				<a href="broadcast.php">Notification Menu</a> | 
			<?php } ?>
	 <a href="logout.php">Logout</a>
	
<hr>


<h4>Welcome back <strong><?php echo $_SESSION['username'] ?></strong></h4>



This is example web push notification from <a href="http://seegatesite.com">seegatesite.com</a>, wait your notify please 🙂
 <!-- Jquery -->
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <!-- Notifikasi Script -->
 <script src="mynotif.js"></script>
	</body>
</html>

Explanation :

Notification script will be executed every 30 seconds.

Create a file that will be called by the Jquery ajax

Copy the following code and save it in a file ajax.php

<?php SESSION_START(); 
include "isLogin.php"; 
include "dbconn.php"; 
include "sql.php"; 
$sql = new sql(); 
$array=array(); 
$rows=array(); 
$listnotif = $sql->listNotifUser($_SESSION['username']);
foreach ($listnotif[1] as $key) {
	$data['title'] = 'Notification Title';
	$data['msg'] = $key['notif_msg'];
	$data['icon'] = 'http://localhost/notification/avatar2.png';
	$data['url'] = 'http://seegatesite.com';
	$rows[] = $data;
	// update notification database
	$nextime = date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))+($key['notif_repeat']*60));
	$sql->updateNotif($key['id'],$nextime);
}
$array['notif'] = $rows;
$array['count'] = $listnotif[2];
$array['result'] = $listnotif[0];
echo json_encode($array);
?>

Explanation: After 30 seconds, the javascript function will take the list of notification message who never been share and will accommodate the data into an array variable

Create a javascript file that will execute the notification

Copy the following code and save it in a file mynotif.js

$(document).ready(function() {
		checknotif();
	setInterval(function(){ checknotif(); }, 10000);
});
function checknotif() {
	if (!Notification) {
		$('body').append('
<h4 style="color:red">*Browser does not support Web Notification</h4>

');
		return;
	}
	if (Notification.permission !== "granted")
		Notification.requestPermission();
	else {
		$.ajax(
		{
			url : "ajax.php",
			type: "POST",
			success: function(data, textStatus, jqXHR)
			{
				var data = jQuery.parseJSON(data);
				if(data.result == true){
					var data_notif = data.notif;
					
					for (var i = data_notif.length - 1; i >= 0; i--) {
						var theurl = data_notif[i]['url'];
						var notifikasi = new Notification(data_notif[i]['title'], {
							icon: data_notif[i]['icon'],
							body: data_notif[i]['msg'],
						});
						notifikasi.onclick = function () {
							window.open(theurl); 
							notifikasi.close();     
						};
						setTimeout(function(){
							notifikasi.close();
						}, 5000);
					};
				}else{

				}
			},
			error: function(jqXHR, textStatus, errorThrown)
			{

			}
		});	

	}
};

Explanation: The main part of this article, contained in the above code.


$(document).ready(function() {
	checknotif();
	setInterval(function(){ checknotif(); }, 30000);
})

When the page is ready, will execute the javascript checknotif() function  and it is always executed after 30 seconds.

	if (!Notification) {
		$('body').append('
<h4 style="color:red">*Browser does not support Web Notification</h4>

');
		return;
	}

Javascript will check whether the browser supports notification feature

if (Notification.permission !== "granted")
		Notification.requestPermission();
	else {
		$.ajax(
		{
			url : "ajax.php",
			type: "POST",
			success: function(data, textStatus, jqXHR)
			{
				var data = jQuery.parseJSON(data);
				if(data.result == true){
					var data_notif = data.notif;
					
					for (var i = data_notif.length - 1; i &gt;= 0; i--) {
						var theurl = data_notif[i]['url'];
						var notifikasi = new Notification(data_notif[i]['title'], {
							icon: data_notif[i]['icon'],
							body: data_notif[i]['msg'],
						});
						notifikasi.onclick = function () {
							window.open(theurl); 
							notifikasi.close();     
						};
						setTimeout(function(){
							notifikasi.close();
						}, 8000);
					};
				}else{

				}
			},
			error: function(jqXHR, textStatus, errorThrown)
			{

			}
		});	

	}

The browser will submit a request to web push notification. Users will get a request like the following picture:

Web Push Notification Alert Seegatesite.com

If the access receipt, then javascript will execute ajax to check for notification of each user.

var theurl = data_notif[i]['url'];
var notifikasi = new Notification(data_notif[i]['title'], {
                                  icon: data_notif[i]['icon'],
                                  body: data_notif[i]['msg'],
		});
notifikasi.onclick = function () {
	window.open(theurl); 
	notifikasi.close();     
};
setTimeout(function(){
	notifikasi.close();
}, 8000);

To show notification with the code above.

Lets check from the browser http://localhost/notification.

Finish, Any question ? Download link below to get full source

Url : http://wp.me/a65Dpx-Fx

password : seegatesite.com

Okay, thus article about how to make web push notification in PHP, JQuery, Ajax and MySQL, hope usefull 🙂

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: