0

I create a notification system on my project, you get notification from a table on db named "notification" with this structure :

---------------------------------
| ID | TITLE | VIEWED | ID_USER |
---------------------------------
| 1  |  test |    0   |    15   |
---------------------------------
| 2  | test2 |    1   |    12   |
---------------------------------

and I get notification by ID user and if the viewed is 0 I add the bell with count not viewed notification.

but the problem is you need to refresh the page to get the notification, so my question is: is there any method to async notification? that means when you received the notification you get the bell at the same time, you don't need to refresh the page

sayou
  • 893
  • 8
  • 29
  • Strictly in php no. You have to use javascript to either poll at regular interval or push notification via a websocket – grunk Apr 17 '19 at 15:03

2 Answers2

1

You need to use a websockets library like Ratchet (http://socketo.me) or similar.

How to create websockets server in PHP

Z .
  • 12,657
  • 1
  • 31
  • 56
1

You can't do this strictly in PHP, but you can use a javascript function, on a loop, to run an AJAX request to a PHP file, every 5 seconds or so, to see if the logged in user has received any notifications recently. Which the PHP files responds with a json array with the notification details for the ajax request to enter into the DOM.

For my example, I'll be using jQuery in my script to run ajax.

HTML file (index.php)

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script>
      var userid = "<?php echo $_SESSION['id']; ?>";

      setInterval(NotificationRequest, 5000); //will run the function 'NotificationRequest' every 5 seconds
      function NotificationRequest() {
        $.ajax({
          url: 'checknoti.php', //the php file to request
          dataType: 'text',
          data: {data : userid},
          method: 'POST',
          success: function(result) {
            $('div#notification').html(result); //insert result from file to inside the div element
          }
        });
      }
    </script>
  </head>
  <body>
    <h1>Notification List</h1>
    <div id="notification"></div>
  </body>
</html>

PHP file (checknoti.php)

$conn = mysqli_connect("127.0.0.1", "username", "password", "database");
$userID = $_POST['data'];

$sql = "SELECT * FROM `notification` WHERE `ID_USER`='$userID' AND `VIEWED`='0'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_accoc($result);

echo $row['title'];

This script (not exactly), should result in the ajax request asking the server for a notification that hasn't been viewed by the user yet, then the html will will update the text inside the DIV (with id "notification"), with the echod notification title.

More on included methods:
- https://www.w3schools.com/jsref/met_win_setinterval.asp
- http://api.jquery.com/html/
- http://api.jquery.com/jQuery.Ajax/

Andrew
  • 34
  • 7