And Apparently the Notification System Is Broke Again Yay

Real-Time-Notification-System-in-PHP-and-AJAX

Ever wonder how social media websites pop up a notification for every action that happens on your timeline?

This real-fourth dimension notification organisation keeps track of every activity you and your friends do on these social channels. Notifications form a big part of the existent-time engagement feature of these platforms. Fifty-fifty you are not online, you lot could still receive these notifications. A PHP notification system could be easily built using a mix of vanilla PHP and JavaScript. This system provides real-time notification in a PHP powered application.

In this article, I volition show you how to create a simple notification organization by using PHP and AJAX. I will besides use jQuery and Bootstrap. For the purpose of this article, I'm assuming that you have already signed up on Cloudways which provides All-time PHP Hosting and has launched a server with the PHP application.

PHP Hosting: Best PHP 7 & PHP 5.six Spider web Hosting

Let's go started.

Import Tables in Database

Cloudways has custom-congenital MySQL manager and you go a pre-built database with every PHP awarding. Just move to the Application Access area and launch the database manager.

Now run the following query in the SQL box.

Ready 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 Non NULL,   `comment_status` int(1) NOT Cipher  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;   Modify TABLE `comments`   ADD PRIMARY Central (`comment_id`);   ALTER TABLE `comments`   MODIFY `comment_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=xiv;        

This query will create a tabular array comments and its four columns 'comment_id' 'comment_subject' 'comment_text' and comment_status. All user comments will exist entered in this database and then the notifications will exist generated.

Cease Wasting Time on Servers

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

Create Navigation And Course To Display Realtime Notifications

I will use the bones navigation and Bootstrap forms by declaring the CDN. Elementary re-create and paste the lawmaking in the index.php file.

<!DOCTYPE html>  <html>  <head>   <championship>Notification using PHP Ajax Bootstrap</championship>   <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/iii.3.vii/js/bootstrap.min.js"></script>  </head>  <body>   <br /><br />   <div course="container">    <nav class="navbar navbar-inverse">     <div form="container-fluid">      <div grade="navbar-header">       <a class="navbar-brand" href="#">PHP Notification Tutorial</a>      </div>      <ul class="nav navbar-nav navbar-correct">       <li class="dropdown">        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><bridge class="characterization characterization-pill label-danger count" style="border-radius:10px;"></bridge> <span course="glyphicon glyphicon-bell" style="font-size:18px;"></bridge></a>        <ul grade="dropdown-menu"></ul>       </li>      </ul>     </div>    </nav>    <br />    <form method="postal service" id="comment_form">     <div form="form-group">      <label>Enter Bailiwick</label>      <input type="text" proper name="subject" id="discipline" class="class-control">     </div>     <div form="form-group">      <label>Enter Annotate</label>      <textarea name="annotate" id="comment" class="grade-control" rows="v"></textarea>     </div>     <div class="grade-group">      <input type="submit" name="post" id="mail" grade="btn btn-info" value="Post" />     </div>    </grade>    </div>  </torso>  </html>

Insert New Records in Database

Create a connect.php file to create a database connection. Add together the post-obit 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["discipline"]);  $comment = mysqli_real_escape_string($con, $_POST["comment"]);  $query = "INSERT INTO comments(comment_subject, comment_text)VALUES ('$subject area', '$comment')";  mysqli_query($con, $query);  }  ?>

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

Related:Adding Push Notification in PHP

Fetch Records and Send to AJAX Call

For this action, create a new file named fetch.php. This volition check whether the AJAX view is updated with new comments. If not, information technology volition select unique comments and testify them in the notification window. In one case the user has seen these notifications, the status would be updated to reflect that these notifications have been reviewed. Hither, I volition ship the $data array to the AJAX call for updating the view.

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

Paste the following lawmaking 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 = ane WHERE comment_status=0";    mysqli_query($con, $update_query); }  $query = "SELECT * FROM comments Club 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"].'</stiff><br />   <small><em>'.$row["comment_text"].'</em></small-scale>   </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); } ?>

Submit Course and Update HTML with AJAX

Now comes the interesting function!

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.

At present, I volition create a submit method in jQuery which volition 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 volition be shown in the Bootstrap's ruby-red pill. Here is the complete code that yous 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:"Postal service",   data:{view:view},   dataType:"json",   success:role(data)    {     $('.dropdown-menu').html(information.notification);     if(information.unseen_notification > 0)    {     $('.count').html(information.unseen_notification);    }    }   });  }  load_unseen_notification();  // submit form and get new records  $('#comment_form').on('submit', role(event){  outcome.preventDefault();   if($('#subject').val() != '' && $('#comment').val() != '')   {    var form_data = $(this).serialize();    $.ajax({     url:"insert.php",    method:"Mail service",    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', part(){   $('.count').html('');   load_unseen_notification('yep');  });  setInterval(role(){   load_unseen_notification();;  }, 5000);  });  </script>        

Testing The PHP Notification System

Now information technology'due south time to examination the notification organization. Y'all will see a window like this:

Enter the discipline and the annotate, and then submit the form. You lot will get the new notification (see the post-obit prototype) when you click the dropdown.

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

Final Words

Notifications offering a quick view of all the actions performed on the website. Y'all tin can easily click them in the dropdown listing and optionally carry out further actions.

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 by using Optimization Tools and performing Server configuration.

This article presents a bones real-fourth dimension notification organisation in PHP that could exist further extended to fit your requirements.

If you find whatsoever queries and questions, feel costless to comment below.

Share your opinion in the comment section. Comment At present

Share This Article

Customer Review at

"Cloudways hosting has one of the best customer service and hosting speed"

Sanjit C [Website Developer]

gardnersafelip.blogspot.com

Source: https://www.cloudways.com/blog/real-time-php-notification-system/

0 Response to "And Apparently the Notification System Is Broke Again Yay"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel