This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Creating Real Time Notification System in PHP and AJAX

Updated on February 22, 2023

7 Min Read
Php notification

Push Notification is a feature that helps you send customized real-time messages to display in browsers like Chrome, Firefox, Safari, etc. Push Notification is web applications’ most used communication channel to stay connected with users.

No matter what website you visit, you’d likely see a notification consent alert to allow or block notifications. These notifications help users get updated with news, chat, emails, and time-bound data like offers and discounts.

PHP push notifications provide real-time notifications on every PHP-powered application and keep your users updated on all activities on your different web pages and social channels.

If you’re still here, you probably want to know how to create PHP notifications – right?
The good news is that you can easily build a PHP notification system via a mix of vanilla PHP and JavaScript.

In this article, I will cover easy steps to create a simple notification system using PHP, AJAX, or MySQL. I will also use jQuery and Bootstrap.

Supercharged Managed PHP Hosting – Improve Your PHP App Speed by 300%

Why Is It Important to Add Push Notifications

Push notifications either help your mobile app succeed or make it fail. Adding a notification highlight is one of the strategies used by many companies to keep their users engaged with their apps.

When used properly, push notifications effectively help boost customer retention rates and improve engagement and user experience.
However, inefficient or overuse of push notifications can be a problem for user experience, resulting in users unsubscribing or uninstalling the application.

Push notifications are a strong marketing tool and an effective channel to communicate with users and stimulate app engagement. App publishers can send push notifications anytime since users don’t have to have the app running at all times to receive them.

However, many users find push notifications aggravating and ranking.

As a best practice, use it cautiously to avoid misuse. Remember that push notification isn’t a one size fits all thing. What works with other apps may not work with every app.

Nothing as Easy as Deploying PHP Apps on Cloud

With Cloudways, you can have your PHP apps up and running on managed cloud servers in just a few minutes.

How Do Push Notifications Work

Real-time notifications work by sending clickable prompts to a browser or app that notify or alert users about activity related to the app, like sports score, a flash sale, or a coupon.

Push notifications can either be a pop-up message displayed on the browser or a text message sent to the user. When the user taps/click the notification message, they will be redirected to the website or launch the app.

In geek terms, upon receiving a network request, a push service verifies it and sends a push message to the appropriate browser or app. The message is held in a queue until the app or browser reconnects if it is offline.

Developers have no control over the push services that individual browsers choose to use. But since every push service receives the same API call, this isn’t too big of a problem. In other words, it doesn’t matter who runs the push service – FCM or Firebase Cloud messaging. You just need to ensure that your API call is valid.

Step 1: Import Tables in Database

Cloudways cloud application hosting has a custom-built MySQL manager, and you get a pre-built database with every PHP application. Just move to the Application Access area and launch the database manager.

Now run the following query in the SQL box.

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";

SET time_zone = "+00:00";


CREATE TABLE `comments` (

 `comment_id` int(11) NOT NULL,

 `comment_subject` varchar(250) NOT NULL,

 `comment_text` text NOT NULL,

 `comment_status` int(1) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=latin1;


ALTER TABLE `comments`

 ADD PRIMARY KEY (`comment_id`);


ALTER TABLE `comments`

 MODIFY `comment_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14;

This query will create a table comments and its four columns ‘comment_id’ ‘comment_subject’ ‘comment_text’ and comment_status. All user comments will be entered in this database and then the notifications will be generated.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Step 2: Create Navigation And Form To Display Realtime Notifications

I will use the basic navigation and Bootstrap forms by declaring the CDN. Simply copy and paste the code into the index.php file.

<!DOCTYPE html>

<html>

<head>

 <title>Notification using PHP Ajax Bootstrap</title>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>

 <br /><br />

 <div class="container">

  <nav class="navbar navbar-inverse">

   <div class="container-fluid">

    <div class="navbar-header">

     <a class="navbar-brand" href="#">PHP Notification Tutorial</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:18px;"&gt;</span></a>

      <ul class="dropdown-menu"></ul>

     </li>

    </ul>

   </div>

  </nav>

  <br />

  <form method="post" id="comment_form">

   <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 Comment</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" />

   </div>

  </form>


 </div>

</body>

</html>

Step 3: Insert New Records in Database

Create a connect.php file to create a database connection. Add the following code in it:

<?php

$con = mysqli_connect("localhost", "root", "", "notif");

?>

You might be interested in: How To Connect MySQL Database With PHP Websites

Next, I will create insert.php and simply insert new comments in MySQL through the following code:

<?php

if(isset($_POST["subject"]))

{

include("connect.php");

$subject = mysqli_real_escape_string($con, $_POST["subject"]);

$comment = mysqli_real_escape_string($con, $_POST["comment"]);

$query = "INSERT INTO comments(comment_subject, comment_text)VALUES ('$subject', '$comment')";

mysqli_query($con, $query);

}

?>

This code snippet is pretty much self-explanatory. It gets the form values and then pushes them to the database tables.

Related: Adding Push Notification in PHP

Step 4: Fetch Records and Send to AJAX Call

For this action, create a new file named fetch.php. This will check whether the AJAX view is updated with new comments. If not, it will select unique comments and show them in the notification window. Once the user has seen these notifications, the status will be updated to reflect that these notifications have been reviewed.

You might be interested in: Build Live Search Box Using PHP, MySQL And AJAX

Paste the following code in the fetch.php file:

<?php

include('connect.php');

if(isset($_POST['view'])){

// $con = mysqli_connect("localhost", "root", "", "notif");

if($_POST["view"] != '')

{
   $update_query = "UPDATE comments SET comment_status = 1 WHERE comment_status=0";
   mysqli_query($con, $update_query);
}

$query = "SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5";
$result = mysqli_query($con, $query);
$output = '';

if(mysqli_num_rows($result) > 0)
{

while($row = mysqli_fetch_array($result))

{

  $output .= '
  <li>
  <a href="#">
  <strong>'.$row["comment_subject"].'</strong><br />
  <small><em>'.$row["comment_text"].'</em></small>
  </a>
  </li>

  ';
}
}

else{
    $output .= '<li><a href="#" class="text-bold text-italic">No Noti Found</a></li>';
}

$status_query = "SELECT * FROM comments WHERE comment_status=0";
$result_query = mysqli_query($con, $status_query);
$count = mysqli_num_rows($result_query);

$data = array(
   'notification' => $output,
   'unseen_notification'  => $count
);

echo json_encode($data);
}
?>

Step 5: Submit Form and Update HTML with AJAX

Now comes the interesting part!

In the previous step, I sent the data array, which will be caught by the AJAX response for updating the inner HTML on the navigation bar.

Now, I will create a submit method in jQuery which will validate the input data, and select the latest notification(s), which I have inserted in insert.php. In the next onclick function, I will update the count which will be shown in the Bootstrap’s red pill. Here is the complete code that you need to paste in the index.php.

<script>

$(document).ready(function(){

// updating the view with notifications using ajax

function load_unseen_notification(view = '')

{

 $.ajax({

  url:"fetch.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();

// submit form and get new records

$('#comment_form').on('submit', function(event){
 event.preventDefault();

 if($('#subject').val() != '' && $('#comment').val() != '')

 {

  var form_data = $(this).serialize();

  $.ajax({

   url:"insert.php",
   method:"POST",
   data:form_data,
   success:function(data)

   {

    $('#comment_form')[0].reset();
    load_unseen_notification();

   }

  });

 }

 else

 {
  alert("Both Fields are Required");
 }

});

// load new notifications

$(document).on('click', '.dropdown-toggle', function(){

 $('.count').html('');

 load_unseen_notification('yes');

});

setInterval(function(){

 load_unseen_notification();;

}, 5000);

});

</script>

Step 6: Testing The PHP Notification System

Now it’s time to test the notification system. You will see a window like this:

Enter the subject and the comment, and then submit the form. You will get the new notification (see the following image) when you click the dropdown.

 

GitHub:  https://github.com/shahroznawaz/php-notifications

Improve Your PHP App Speed by 300%

Cloudways offers you dedicated servers with SSD storage, custom performance, an optimized stack, and more for 300% faster load times.

Final Words

At the moment, push notifications are the most demanding functionality that’s implemented in websites and apps. So if you’re developing a web application or an app and integrating push notification functionality, then you’re off to a good start.

Enhancing user engagement on a content-rich website is made effortless with PHP notifications. By delivering updates that align with users’ interests, you can drive them back to your platform time and again. The beauty lies in the fact that setting up push notifications using PHP web hosting is a straightforward endeavor. While it may demand a certain level of effort, the results are well worth it as you establish a dynamic connection with your audience.

The pros and cons largely depend on the usage and implementation of this method. Advantages include better UX and updating users on time etc. The possible technical disadvantage includes the load on MySQL, which can be dealt with using Optimization Tools and performing Server configuration.

Q: What are the benefits of using a real-time notification system in PHP?

A: A real-time notification system in PHP offers several benefits, including timely updates and user communication. It enables push notifications, delivering specific news, chat messages, emails, and time-sensitive information instantly. This system operates in real-time, facilitating interactive communication between the server and clients.

Q: Can I integrate third-party messaging platforms or services with a real-time PHP notification system?

A: Yes, you can integrate third-party messaging platforms or services seamlessly with a real-time PHP notification system. PHP provides various APIs and libraries that allow easy integration with popular messaging platforms such as Twilio, Firebase Cloud Messaging (FCM), Pusher, or custom solutions.

Q: Can I send real-time notifications to multiple users simultaneously using PHP?

A: Yes, you can send real-time notifications to multiple users simultaneously using PHP. Technologies like WebSockets or server-sent events (SSE), combined with PHP frameworks or libraries, enable this functionality.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now