Php Form Dynamically Upload Picture and Auto on a Webpage Live

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

Always wonder how social media websites pop upwardly a notification for every activity that happens on your timeline?

This real-fourth dimension notification system keeps rail of every action you and your friends do on these social channels. Notifications form a big part of the real-time date characteristic of these platforms. Even you are not online, you 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 commodity, I volition prove yous how to create a simple notification system past using PHP and AJAX. I will besides use jQuery and Bootstrap. For the purpose of this article, I'one thousand bold 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: All-time PHP seven & PHP 5.6 Web Hosting

Let'south get started.

Import Tables in Database

Cloudways has custom-congenital MySQL manager and yous get a pre-congenital database with every PHP awarding. Simply movement to the Application Access surface 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) Non NULL,   `comment_subject` varchar(250) NOT Cipher,   `comment_text` text Not Goose egg,   `comment_status` int(1) NOT Cipher  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;   ALTER TABLE `comments`   ADD Master 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 so the notifications will be generated.

End Wasting Time on Servers

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

Create Navigation And Form To Display Realtime Notifications

I volition utilise the basic navigation and Bootstrap forms by declaring the CDN. Simple re-create and paste the code in the index.php file.

<!DOCTYPE html>  <html>  <caput>   <title>Notification using PHP Ajax Bootstrap</title>   <script src="https://ajax.googleapis.com/ajax/libs/jquery/iii.ane.0/jquery.min.js"></script>   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.iii.half dozen/css/bootstrap.min.css" />   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.seven/js/bootstrap.min.js"></script>  </head>  <body>   <br /><br />   <div class="container">    <nav class="navbar navbar-inverse">     <div form="container-fluid">      <div class="navbar-header">       <a class="navbar-brand" href="#">PHP Notification Tutorial</a>      </div>      <ul class="nav navbar-nav navbar-right">       <li course="dropdown">        <a href="#" class="dropdown-toggle" information-toggle="dropdown"><span form="label characterization-pill characterization-danger count" style="border-radius:10px;"></span> <span form="glyphicon glyphicon-bell" way="font-size:18px;"></span></a>        <ul form="dropdown-menu"></ul>       </li>      </ul>     </div>    </nav>    <br />    <class method="mail" id="comment_form">     <div course="grade-group">      <label>Enter Subject</label>      <input type="text" proper noun="discipline" id="field of study" class="form-control">     </div>     <div class="course-group">      <label>Enter Comment</characterization>      <textarea proper noun="comment" id="comment" class="form-control" rows="five"></textarea>     </div>     <div class="form-group">      <input type="submit" name="post" id="post" class="btn btn-info" value="Post" />     </div>    </form>    </div>  </body>  </html>

Insert New Records in Database

Create a connect.php file to create a database connection. Add 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["bailiwick"]))  {  include("connect.php");  $subject field = mysqli_real_escape_string($con, $_POST["bailiwick"]);  $comment = mysqli_real_escape_string($con, $_POST["comment"]);  $query = "INSERT INTO comments(comment_subject, comment_text)VALUES ('$field of study', '$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 button Notification in PHP

Fetch Records and Transport to AJAX Telephone call

For this activeness, 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 condition would be updated to reflect that these notifications have been reviewed. Here, I will send the $information assortment to the AJAX phone call for updating the view.

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

Paste the post-obit 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 up comment_status = 1 WHERE comment_status=0";    mysqli_query($con, $update_query); }  $query = "SELECT * FROM comments ORDER Past comment_id DESC LIMIT five"; $result = mysqli_query($con, $query); $output = '';  if(mysqli_num_rows($result) > 0) {  while($row = mysqli_fetch_array($effect))  {    $output .= '   <li>   <a href="#">   <strong>'.$row["comment_subject"].'</potent><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); } ?>

Submit Form and Update HTML with AJAX

Now comes the interesting part!

In the previous pace, I sent the information assortment, 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 side by side onclick function, I will update the count which will be shown in the Bootstrap's red pill. Here is the consummate lawmaking that yous need to paste in the index.php.

<script>  $(certificate).ready(office(){  // 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: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(effect){  event.preventDefault();   if($('#bailiwick').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', office(){   $('.count').html('');   load_unseen_notification('yes');  });  setInterval(office(){   load_unseen_notification();;  }, 5000);  });  </script>        

Testing The PHP Notification System

Now it'due south time to test the notification system. You lot volition see a window like this:

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

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

Final Words

Notifications offer a quick view of all the actions performed on the website. You can easily click them in the dropdown list and optionally bear 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 arrangement in PHP that could be further extended to fit your requirements.

If you find any queries and questions, feel free to annotate beneath.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

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

Sanjit C [Website Developer]

normanabildromfor58.blogspot.com

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

0 Response to "Php Form Dynamically Upload Picture and Auto on a Webpage Live"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel