Pusher Notifications(Php and Jquery)

It is very useful to be able to produce real time notifications in php.
Hence the need of third party libraries like Pusher that creates notifications on the go with basic php and jquery(or any other language).
But then, one could develop a basic notification system using php , mysql(i) jquery and some ajax.

For this system create a notification table and a test table: table in which we will perform the CRUD……which I called “user”
Structure of my system is very basic . Nine files all at the same level in the same directory which I named notifications.The files include db.php,updte_notif.php,footer.php,functions.php,header.php,index.php,init.php,styles.css,user.php
:) Sorry i’m not very creative with names.
I’ll try to describe the purpose of each file and its interactions with the others
db.php: Holds the database connections

<?php
 $con = new mysqli(‘localhost’,’root’,’’,’test’);
?>

init.php : initialize all the php files in one place Ob_start for output buffering and session_start for my session variables

<?php
ob_start();
session_start();

require’db.php’;

?>

header.php : header of my 2 main files index and user.php

<?php require’init.php’ ?>
<!DOCTYPE html>
<html lang=”en”>

<head>
 <meta charset=”UTF-8">
 <meta name=”viewport” content=”width=device-width, initial-scale=1">
 <title>Document</title>
 <! — Latest compiled and minified CSS →
 <link rel=”stylesheet” href=”
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<! — custom styles →
 <link rel=”stylesheet” href=”styles.css”>

<! — jQuery library →
 <script src=”
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<! — Latest compiled JavaScript →
 <script src=”
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
 <div class=”container”>

Notice my init.php file on line one , the rest are meta tags, bootstrap cdn and a link to custom css file.

index.php : Main page of app this page is used to create users and insert into user table(This is the test table I earlier referred to ).

The code checks for form submission with the line if(isset($_POST[‘submit’])) then gets the value of the name form field inserts into table…Next it checks to see if the query was successful and if it was then it will insert some data into notifications table that is a body and time of creation.
Finally it simply echoes a bootstrap alert box.

<?php include’header.php’ ?>
<div class=”row”>
 <div class=”col-xs-12">
 <h1 class=’text-center bg-info’>Create a new user</h1>
 </div>
 <div class=”col-xs-12">
 <?php
 if(isset($_POST[‘submit’])){

$name = $_POST[‘user’];
 $sql = “INSERT INTO users(name) VALUES(‘{$name}’)”;

$query = $con->query($sql);
 if($query){

$body = “New user with username : {$name} created”;
 $read = 0;
 $date = date(“Y-m-d H:i:s”);
 
 $sql2 = “INSERT INTO notifications(body,opened,date) VALUES(‘{$body}’,$read,’{$date}’)”;
 $query2 = $con->query($sql2); 
 
 $mes = <<<END_TEXT
 <div class=”alert alert-success alert-dismissible fade in”>
 <a href=”#” class=”close” data-dismiss=”alert” aria-label=”close”>&times;</a>
 <strong>Success!</strong> User created.
 </div>
END_TEXT;
 echo $mes;
 }
 }
 
 ?>
 <form action=”” method=”post”>
 <div class=”form-group”>
 <label for=””>New user</label>
 <input type=”text” name=”user” required placeholder=”New user…” class=”form-control”>
 </div>
 <input type=”submit” name=”submit” class=”btn btn-primary btn-block”>
 </form>
 </div>
</div>

Next we create user.php where will receive notifications about our newly created users. It is a ajax function $.ajax because we want to constantly check after , let’s say 2 seconds and we output the result in a div with id notifs. The function is called getNotifs and is passed as callback in the setInterval(for more info on how to use it google on it please:) ) js function.

<?php include’header.php’ ?>
<div class=”row”>
 <div class=”col-xs-12">
 <div id=”notifs”>

</div>
 <script>
 $(document).ready(function() {
 function getNotifs() {
 $.ajax({ 
 url: ‘functions.php’,
 success: function(data) {
 if (!data.error) {
 $(‘#notifs’).html(data);
 }
 }
 })
 }

setInterval(getNotifs, 2000);

})

</script>
 </div>
</div>

The parameter passed to the ajax object with key url is the url of the script that will get all notifications after 2 seconds which i called functions.php

Next functions.php

<?php include’init.php’ ?>
<?php

/**we run the query that will get all the notifications with column opened = 0 which means it has not been opened **/

$sql = “SELECT * FROM notifications where opened = 0 order by id desc”;
 $query = $con->query($sql);
 while($row = $query->fetch_assoc()):

/**get the date , id of notification and its body Remember the table is filled when we create a new user**/

$date = $row[‘date’];
 $id = $row[‘id’];
 $body = $row[‘body’];
?>

//read the data and output it

<div id=”<?php echo $id ?>” class=”notif alert alert-info alert-dismissible fade in”>
 <a href=”#” class=”close” data-dismiss=”alert” aria-label=”close”>&times;</a>
 <strong>New User!</strong>
 <?php echo $body ?> at<br>
 <?php echo $date ?>
</div>

<?php 
 //end the loop

endwhile;
 
?>

<script>
 $(document).ready(function() {

/** This is to be performed when the user clicks on a specific notification . It gets the id of that notification and stores in a variable called id and passed to the ajax request **/

$(“.notif”).click(function() {
 var id = $(this).attr(‘id’);
 $.ajax({
 url: ‘updte_notif.php’,
 type: ‘GET’,
 data: {
 id: id
 },

})
 })

})

</script>

The script part of this code is to extract the id of a specific notification on click using jquery then pass it to the ajax object as a key in the data parameter.The type parameter is GET…..and the url is updte_notif.php…This simply means that a GET array will be created and that one of it’s keys will be called id and will have as value the id of the notif ication that was clicked.

Next updte_notif.php

<?php
 include’init.php’ ;
 if(isset($_GET[‘id’])){
 $id = $_GET[‘id’];
 $sql = “UPDATE notifications set opened = 1 where id = $id”;
 $query = $con->query($sql);
 }

?>

We get the database from the init.php file, check if the index id is present this index contains the value of the id of the notification that was clicked and this id will be used to run the query. That notification is updated and its column called opened will be set to 1 which means it has been read.

Our footer.php

</div>

</body>

</html>

And finally our styles.css

#notifs {
 width: 50%;
 position: relative;
 z-index: 1;
 float: right;
 margin-top: 20px;
 padding: 5px;
}

.notif {
 width: 50%;
 float: right;
 margin: 2px 5px;
}

Thank you and feel free to criticise my logic and point out any bug.
This was purely procedural I avoided using OOP but one could do this with OOP
I will come back to the post later and share my oop version of it.

Seke Camille