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.

Join us for Deploy in Austin (21-22 Jan) or sign-up to attend virtually. Register Now→

Creating Real Time Notification System in PHP and AJAX

Updated on February 22, 2023

9 Min Read
How to Create Real-Time Notification System in PHP with AJAX Polling

What comes to your mind when you hear the word push notification? Something popping up on your browser or an annoying ad? Well, that’s very close to its meaning and use.

With Push Notifications, you can easily deliver customized messages in real-time that will appear in the browser, such as Chrome, Firefox, Safari, and others. And it’s commonly used by web apps to maintain user connectivity.

Regardless of the site you visit, you will most likely receive a notification consent prompt asking you to enable or restrict alerts. These notifications oftenly provide news, chat, emails, and offers & discounts to the users.

Now, you may think how do we create these notifications on PHP-based apps? Well, there are multiple ways to create real-time notification systems, such as:

  • Ajax Polling
  • Long Polling
  • Web-Sockets
  • Server-Sent Events (SSE)

In this blog, we have covered the Ajax polling method to create a Real-time Notification System in PHP, so let’s see how it works.

Pre-Requisites

First things first, to create the PHP real-time notification system, you need to have a slight understanding of the following things, or else don’t worry, we have the code for you to help. 😉

  • PHP and MySQL
  • HTML, CSS, and JavaScript
  • jQuery and AJAX

Ready to Take Your PHP Applications to the Next Level?!

With Cloudways, you have the flexibility to experiment, optimize, and perfect every aspect of your PHP applications. Try Cloudways with a 3-day free trial and deploy your PHP projects effortlessly.

How to Create a Real-Time Notification System in PHP with AJAX Polling (Step-by-Step Guide)

Simply follow the easy steps below to create a real-time notification system in PHP with AJAX polling:

Step 1: Create a Table in the Database

If you are a Cloudways user, you’re in luck.

  • Go to the Cloudways Platform and sign in with your login details. Not a Cloudways user? Sign up for free and enjoy their 3-day free trial, without even giving your credit card details.
  • Launch the database manager by clicking the “Launch Database Manager” button.

Launch Database Manager

  • Run the following query.

💡Note: If you are not a Cloudways user, then you may create the table as advised.

SQL Query:

CREATE TABLE `comments` (
`comment_id` INT AUTO_INCREMENT PRIMARY KEY,
`comment_subject` VARCHAR(250) NOT NULL,
`comment_text` TEXT NOT NULL,
`comment_status` TINYINT(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Inserting SQL Query in Cloudways Database Manager

  • Once you’ve executed the query, you will see the following Output.

SQL Query Output for Table Creation

Step 2: Create a Form and Navigation Process for Notifications

We will create basic navigation and Bootstrap form by declaring the CDN. You can modify it as per your liking, but if you want to test the same code, copy the following code and add it to the index.php file of your application.

💡Note: Clear the file before adding the code. For Cloudways users, you will see a default index.php file once you launch a custom PHP app, delete the file under public_html to create a new one with the code we have shared below.

Before we share the code, here’s what you need to do:

  • Launch the SSH terminal to get into your server and access the application path to make required changes. You can use vim or nano to edit the file.

Launching Cloudways SSH Terminal

  • Once you are in the server, you can remove the default index.php file & add the following code:

Default PHP Application Index.php file

Removing Default Index.php file

Removing Default Index.php file

Index.php Code:

<!DOCTYPE html>
<html>
<head>
<title>PHP Real-time Notifications System</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 System</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;"></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>

Index.php file code

Step 3: Creating a Database Connection

Now, we will create a connect.php file to handle the connection to the MySQL database. Make sure you add your database details correctly, such as dbuser, dbname, and db password.

If you are a Cloudways user, you will find your application’s database details in the application management tab:

Launching Cloudways Application Database Manager

Now, add the following code to your connect.php file. Also, modify the credentials with your concerned application database details.

Creating Connect.php file

Inserting Connect.php File Code

Connect.php Code:

<?php
$host = "localhost";
$username = "dbuser"; // Your DB username
$password = "dbpassword"; // Your DB password
$dbname = "dbname"; // Your DB name

$con = mysqli_connect($host, $username, $password, $dbname);

if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>

Verify the details or connection of the file using the command php -f connect.php to proceed further.

Testing Database Connection

Step 4: Insert Comments into Database

  • Now, we will create an insert.php file to insert new comments into the database. We have added $comment_status for query insertion.

Creating Insert.php file

  • Copy the following code into the insert.php file.

Inserting Code into Insert.php file

Insert.php Code:

<?php
if(isset($_POST["subject"]) && isset($_POST["comment"])) {
include("connect.php");

$subject = mysqli_real_escape_string($con, $_POST["subject"]);
$comment = mysqli_real_escape_string($con, $_POST["comment"]);
$comment_status = 0; // Default status as integer

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

if (mysqli_query($con, $query)) {
echo "New comment added successfully.";
} else {
echo "Error: " . mysqli_error($con);
}

mysqli_close($con);
}
?>

 

Step 5: Fetch Notifications

  • In this step, we will create the fetch.php file under public_html to fetch the notifications in real-time.

Creating Fetch.php File under Public_html

  • Doing so will help you verify whether there are any new comments added to the AJAX view.

Inserting code into Fetch.php file

  • Add the following code to the fetch.php file.

Fetch.php Code:

<?php
include("connect.php");

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

$count_query = "SELECT COUNT(*) AS count FROM comments WHERE comment_status = 0";
$count_result = mysqli_query($con, $count_query);
$row = mysqli_fetch_assoc($count_result);
$unseen_notification = $row['count'];

if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$output .= '
<li>
<a href="#">
<strong>' . $row["comment_subject"] . '</strong><br />
<small>' . $row["comment_text"] . '</small>
</a>
</li>
<li class="divider"></li>
';
}
} else {
$output .= '<li>No Notification Found</li>';
}

$data = array(
'notification' => $output,
'unseen_notification' => $unseen_notification
);
echo json_encode($data);
?>

Step 6: Create a Submit Method in jQuery

Now that we are nearing the last steps, we have to create a submit method in jQuery which will validate the input data, and select the latest notification(s), which we have inserted in insert.php. For this, we will add the following code in the index.php file within the body tags as shown below:

Index.php code for submitting method in jQuery

Index.php code for submitting method in jQuery

Index.php code for submitting method in jQuery:

<script>
$(document).ready(function() {
// Function to load notifications
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(); // Initial call to load notifications

// Submit form using AJAX
$('#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");
}
});

// Mark notifications as seen on dropdown click
$(document).on('click', '.dropdown-toggle', function() {
$('.count').html('');
load_unseen_notification('yes');
});

// Set interval to refresh notifications
setInterval(function() {
load_unseen_notification();
}, 5000);
});
</script>

If you want to add the complete index.php code for better clarity, it has to be added in one go. But in this blog, we have divided the steps for a better explanation. Anyway, here’s the complete index.php code:

Complete Index.php Code:

<!DOCTYPE html>
<html>
<head>
<title>PHP Real-time Notifications</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;"></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>

<script>
$(document).ready(function() {
// Function to load notifications
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(); // Initial call to load notifications

// Submit form using AJAX
$('#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");
}
});

// Mark notifications as seen on dropdown click
$(document).on('click', '.dropdown-toggle', function() {
$('.count').html('');
load_unseen_notification('yes');
});

// Set interval to refresh notifications
setInterval(function() {
load_unseen_notification();
}, 5000);
});
</script>
</body>
</html>

Step 7: Access Your Application’s URL

Finally, access your application’s URL now to test the Notification System. And again, Cloudways users can access it directly from the Platform.

Access Cloudways Application URL

💡Note: Please make sure that Varnish is disabled on your application to avoid any inconvenience, as it’s not advised to use Varnish with custom PHP apps.

Disabling Varnish

After accessing the URL, you will see the form that we have created. And that’s it! We can see the Notification system is working fine after submitting the comments.

Adding Comment to test PHP Notification System

PHP Notification System

Wrapping Up!

We were able to develop a Real-Time PHP Notification system using Ajax Polling in this blog. Using AJAX polling in PHP to create a real-time notification system is an easy but efficient technique to inform visitors without requiring them to reload the page. Using this method, you can quickly integrate notifications into your application, which can make it more dynamic and user-friendly. We tested the performed configuration using Cloudways Platform. You may test it for free by signing up with Cloudways or using your own hosting.

Small to medium-sized projects can benefit from AJAX polling, but for bigger, more complicated systems, it’s crucial to take into account other techniques like WebSockets or long polling. Now that you know more about this guide, you may expand and modify your notification system to suit your own requirements. Happy Coding!

1. What is Ajax polling technique?

The technique known as AJAX polling involves the browser periodically requesting updates from the server. This saves us from having to reload the page to check for new alerts.

2. Why did we decide to use this notification system with AJAX polling?

Answer: We chose AJAX polling because it is straightforward to use and suitable for small to medium-sized applications that require real-time updates.

3. Can I get other kinds of notifications using this system?

In response, sure! By making changes to the database and PHP scripts, you may adjust this system to handle any kind of notification, including chat messages, alarms, or updates.

4. Is this approach effective in large-scale settings?

AJAX polling may not be the ideal option for bigger applications as it might put undue strain on the server. To improve performance in certain situations, think about utilizing WebSockets or long polling.

5. Is it possible to modify how frequently the system looks for fresh alerts?

In the JavaScript code, the interval time is readily adjustable. Though you may adjust this to any desired time, it checks by default every 5 seconds.

6. How can I display notifications other than text messages?

To personalize the content of the notice, make changes to the HTML within the fetch.php script. Images, links, and any other material you like to display can be a part of this.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Salwa Mujtaba

Salwa Mujtaba is a Technical Content Writer at Cloudways. With a strong background in Computer Science and prior experience as a team lead in Cloudways Operations, she brings a deep understanding of the Cloudways Platform to her writing. Salwa creates content that simplifies complex concepts, making them accessible and engaging for readers. When she's not writing, you can find her enjoying good music, reading a book, or spending quality time with her family.

×

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