Dynamic Web Notification using PHP and JavaScript Tutorial
In this tutorial, you will learn how to Implement a Dynamic Web Push Notification using PHP and JavaScript. The tutorial aims to provide IT/CS students a reference to learn the usage of JavaScript Notification API and Integrate it with PHP Language and Ajax requests. Here, snippets of a sample application will be provided. Also, I have provided the working source code zip file of the simple program that demonstrates the implementation of dynamic web push notifications.
What is JavaScript Notification API?
JavaScript comes with a Notification application program interface (API). It is an interface used for configuring display notifications to the end users' devices. The Notification methods are available in various web browsers. To know more about the browser compatibility of this API, visit JS Notification's Browser Compatibility.
How can we Implement Dynamic Web Push Notifications using PHP and JS?
As I mentioned above, Notification is a JavaScript API which means push notifications will be triggered using JavaScript. To integrate the said API to have dynamic notification content or information using PHP and MySQL Database, we can simply use HTTP Requests for fetching or retrieving the notification data.
Example
Here are the following snippets for a simple web application that demonstrate the implementation of Dynamic Web Push Notification using PHP and JavaScript.
MySQL Schema
For this demo application, we will be using the following MySQL Schema. Create a database named dummy_db and the table where the notification details will be stored at the notifications table.
Database Connection
The following snippet is a PHP script named db-connect.php. It is a PHP file that contains the scripts for handling the connection between the application and the database.
- <?php
- // Server Host
- $host = "localhost";
- // Server DB Username
- $uname = "root";
- // Server DB Password
- $password = "";
- // Server DB Name
- $dbname = "dummy_db";
- $conn = new mysqli($host, $uname, $password, $dbname);
- if(!$conn){
- }
Interface
The following snippet is an HTML file known as index.html. It contains the HTML script or the page interface elements for displaying the form for saving the notification details into the database.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html, body{
- height: 100%;
- width: 100%;
- }
- body{
- display: flex;
- height: 100%;
- width: 100%;
- flex-direction: column;
- }
- body>nav, body>footer{
- flex-shrink: 1;
- }
- body>main{
- flex-shrink: 1;
- flex-grow: 1;
- overflow: auto;
- margin: 1em 0;
- }
- pre{
- min-height:20vh
- }
- </style>
- </head>
- <body style="background:#eff3fc">
- <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <main class="container-fluid">
- <div class="col-lg-6 col-md-8 col-sm-12 col-xs-12 mx-auto">
- <hr>
- <div class="card mt-3 rounded-0">
- <div class="card-header">
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form action="" id="notif-form">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="title" name="title" required="required">
- </div>
- <div class="mb-3">
- <input type="url" class="form-control rounded-0" id="url" name="url" required="required">
- </div>
- <div class="mb-3">
- <input type="url" class="form-control rounded-0" id="image_url" name="image_url">
- </div>
- <div class="mb-3">
- </div>
- </form>
- </div>
- </div>
- <div class="card-footer py-2">
- <div class="row justify-content-center">
- <div class="col-lg-4 col-md-6 col-sm-10 col-xs-12">
- </div>
- <div class="col-lg-4 col-md-6 col-sm-10 col-xs-12">
- </div>
- </div>
- </div>
- </div>
- </div>
- </main>
- <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
- <div class="container-fluid my-2">
- <div class="text-center">
- </div>
- </div>
- </footer>
- </body>
- </html>
PHP API
Save Notification
The following snippet is a PHP script named save_notification.php. The snippet saves the notification details into the database. By default, the notification details status is set as "unsent".
- <?php
- require_once("db-connect.php");
- $insert_sql = "INSERT INTO `notifications` (`title`, `url`, `image_url`, `description`) VALUES ('{$title}', '{$url}', '{$image_url}', '$description')";
- $insert = $conn->query($insert_sql);
- if($insert){
- $response['status'] = 'success';
- $response['msg'] = 'Notification has been added successfully.';
- }else{
- $response['status'] = 'error';
- $response['msg'] = 'Notification has failed to save. Error: ' . $conn->error;
- }
- ?>
Retrieve Pending Notifications
The following script is a PHP file named get_notifications.php. The script retrieves the pending notification details that will be used for creating the Dynamic Push Notification.
- <?php
- require_once('db-connect.php');
- $notif_sql = "SELECT * FROM `notifications` where `status` = 'unsent'";
- $notif_qry = $conn->query($notif_sql);
- $notifs = [];
- if($notif_qry->num_rows > 0){
- $notifs = $notif_qry->fetch_all(MYSQLI_ASSOC);
- }
Update Notifications
The following snippet is a PHP file named update_notification.php. It is a PHP script that updates the notification details as sent after the web push notification is created.
- <?php
- require_once("db-connect.php");
- $update_sql = "UPDATE `notifications` set `status` = 'sent' where `id` = '{$_POST['id']}' ";
- $update = $conn->query($update_sql);
- if($update){
- $response['status'] = 'success';
- }else{
- $response['error'] = "An error occurred. Erro: ".$conn->error;
- }
JavaScript
Lastly, the following snippet is a JavaScript file known as script.js. It is contains the scripts for submitting the notification form details, retrieving the pending notfications, creating Notification, and display notification to the users' devices.
- /**
- * Get Pending Notifications
- */
- const send_notif = () =>{
- if("Notification" in window){
- if(Notification.permission === 'granted'){
- $.ajax({
- url:"get_notifications.php",
- dataType:'json',
- error: err => {
- console.error(err)
- },
- success:function(data){
- Object.values(data).forEach(notif => {
- var notif_data = {}
- notif_data.icon = "http://localhost/web_notification/test-icon.png";
- notif_data.body = notif.description;
- notif_data.image = notif.image_url;
- var webNotification = WebPushNotification(notif.title, notif.url, notif_data)
- // console.log(webNotification)
- if(webNotification !== undefined){
- /**
- * Update Notification
- */
- update_notification(notif.id)
- }
- })
- },
- complete: ()=>{
- setTimeout(()=>{
- send_notif();
- }, 3000)
- }
- })
- }
- }
- }
- /**
- * Update Notification to sent
- * @param {int(notfication ID)} $id
- * @returns
- */
- const update_notification = ($id) =>{
- return $.ajax({
- url:"update_notification.php",
- method:'POST',
- data:{id:$id},
- dataType:'json',
- error:err=>{
- console.error(err)
- },
- success:function(response){
- if(!!response.status){
- if(response.status == 'success'){
- console.log(`Notification [${$id}] has been updated to sent.`)
- }else{
- console.error(response)
- }
- }else if(!!response.error){
- console.error(response.error)
- }else{
- console.error(response)
- }
- }
- })
- }
- $(document).ready(function(){
- wpn_ask_permission();
- send_notif();
- /**
- * Form Submission
- */
- $('#notif-form').submit(function(e){
- e.preventDefault();
- var _this = $(this)
- _this.find('button').attr('disabled', true)
- var msg = $("<div>")
- msg.hide()
- msg.addClass("alert form-msg")
- $('.form-msg').remove()
- $.ajax({
- url:"save_notification.php",
- method:'POST',
- data:_this.serialize(),
- dataType:"json",
- error: err =>{
- alert("An error occurred while saving the notifcation data.");
- console.error(err)
- _this.find('button').attr('disabled', true)
- },
- success:function(response){
- if(!!response.status){
- if(response.status == 'success'){
- msg.text(response.msg)
- msg.addClass('alert-success')
- _this.prepend(msg)
- msg.show('toggle')
- }else{
- msg.text(response.msg)
- msg.addClass('alert-danger')
- _this.prepend(msg)
- msg.show('toggle')
- }
- }else{
- alert("An error occurred while saving the notifcation data.");
- console.error(response)
- }
- _this[0].reset()
- _this.find('button').attr('disabled', true)
- }
- })
- })
- })
- window.wpn_ask_permission = function (){
- if(!("Notification" in window)){
- alert("Your browser does not support Desktop Notification.");
- console.error("Your browser does not support Desktop Notification.");
- }else{
- console.log(Notification.permission)
- if(Notification.permission !== 'granted' && Notification.permission !== 'denied'){
- Notification.requestPermission().then( permission =>{
- if(permission ==='granted'){
- alert("Notification Permission is granted");
- }else if(permission ==='denied'){
- alert("Notification Permission is not granted");
- }
- location.reload();
- } )
- }
- }
- }
- window.WebPushNotification = function (title="", $action="", data = {}){
- var notification ;
- if(("Notification" in window)){
- if(Notification.permission === 'default'){
- wpn_ask_permission()
- }else if(Notification.permission === 'granted'){
- notification = new Notification(title,data)
- notification.onclick = (event) => {
- window.open($action)
- }
- }
- }
- return notification;
- }
Kindly replace the Notification Icon in the script with your preferred and downloaded notification logo or icon.
There you go! You can now test the application on your end and see if it works properly. I also provided the complete source code zip file on this article and is free to download. The download button is located below this article.
Snapshot
Here are the images of the result of the demo application.
Page Interface
Notification
DEMO Video
That's it! I hope this Dynamic Web Push Notification using PHP and JavaScript Tutorial helps you with what you are looking for and you'll find it useful for your current and future projects.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Comments
Add new comment
- Add new comment
- 4097 views