In the previous tutorial, I developed a chat application using Pusher on my hosting for PHP and discussed the process of setting up a Pusher account and testing the responses of the app. In this tutorial, I will show you how to add a browser and push notification in a PHP chat app. I will use Toastr.js for browser notifications and OneSignal API for push notification in PHP.
Let’s recall the previous tutorial. I included AJAX and pusher.js libraries to work with the messages and the related response. The messages were sent on the click event of the Enter key. Pusher authenticated the messages and and then pass on to the client in the AJAX request.
In the new version, when you get the messages while the app is active, you can set Toast notifications for a quick look at the message.
Here is the AJAX call which takes the PHP file URL and the message data:
// Send AJAX request to the PHP file on server    function ajaxCall(ajax_url, ajax_data) {        $.ajax({            type: "POST",            url: ajax_url,            //dataType: "json",            data: ajax_data,            success: function(response) {                //console.log(response);            },            error: function(msg) {}        });    }
Now when the message is displayed to the user, a Toast notification is also displayed.
Download Tools for Developers Now
We’ll send a download link to your inbox.
Thank You
Your Ebook is on it’s Way to Your Inbox.
What is Toastr:
Toastr is a JavaScript library which is used to make a notification popup. Open this project in Visual Studio Code.
toastr is a JavaScript notification library that is easy to use, and extendable. It allows users to make simple and basic toasts with HTML5 and JavaScript like this: Basically incorporate the records in your HTML page and compose a straightforward line of code like this: toastr.
Host PHP Websites with Ease [Starts at $10 Credit]
- Free Staging
- Free backup
- PHP 8.0
- Unlimited Websites
Show a Toastr with toastr.js
Toastr is a Javascript library for non-blocking notifications. It requires jQuery (I’ve already added jQuery files in previous scripts). Now to add Toastr notifications to the chat app, first add these two scripts in the head tag.
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
Next, I will add the Toastr method in the binding event of the received message which is my_event. Remember I have got the response in the data variable and append it to the message_display div.
// bind the server event to get the response data and append it to the message div    channel.bind('my_event',        function(data) {            //console.log(data);            $('.messages_display').append('<p class = "message_item">' + data + '</p>');            $('.input_send_holder').html('<input type = "submit" value = "Send" class =            "btn btn-primary btn-block input_send" />');            $(".messages_display").scrollTop($(".messages_display")[0].scrollHeight); // Show toastr notification here toastr.options = {               timeOut: 5000,               extendedTimeOut: 0,                fadeOut: 200,                fadeOut: 200            };            toastr.info(data);        });
Now when you send a message to anyone, it shows the Toastr to the recipient. Check out the following screencap:
What is OneSignal PHP:
OneSignal is a multi-platform push notification service and it is totally FREE to use. OneSignal is a benefit that enables push notifications, abstracting points of interest such as the stage the gadget is running on. With the OneSignal plugin, OutSystems applications can send and receive push notifications.
OneSignal in PHP is the quickest and most solid service to send push notifications, in-app messages, SMS, and emails. In our documentation, you’ll be able find resources and training to implement OneSignal’s SDKs, learn how to use OneSignal’s effective dashboard and API, and discover best practices for sending messages.
Show Web Push Notification For Chat Messages
Next, I’ll setup web push notification in the PHP chat application we created. Here I’m going to use the PHP OneSignal API for this: for this, follow these steps:
- Setup the OneSignal account
- Add the application
- Get the app key and the API key
Since the account setup is simple, I will not cover it in this tutorial. If you need help, follow this guide.
When you have successfully created the account, OneSignal will give you a customized script that contains the appID. Add it into the head tag. Here is the script:
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script> Â Â Â <script> Â Â Â Â Â Â Â Â Â Â Â var OneSignal = window.OneSignal || []; Â Â Â Â Â Â Â Â Â Â Â OneSignal.push(function() { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â OneSignal.init({ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â appId: "c7xxbca5-xxxx-4e54-xxxx-ca07exxxx013", Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â autoRegister: false, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â notifyButton: { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â enable: true, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â notifyButton: { Â Â Â Â Â Â Â Â enable: true /* Set to false to hide */ Â Â Â Â }, Â Â Â Â welcomeNotification: { Â Â Â Â Â Â "title": "My Custom Title", Â Â Â Â Â Â "message": "Thanks for subscribing!", Â Â Â Â } Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â Â Â Â }); Â </script>
Once the script is added, you will see the red OneSignal icon appear at the bottom right corner of the window.
Click the icon and subscribe to the notifications. Next, for sending chat notifications to the chat app users, you need to add the send notifications functionality to the app. Basically whenever an app user sends a message, OneSignal will create a notification and sends it to all subscribed persons.
For this, you need to add the following code to message.php page. This code will use the appID and API key for authentication.The function accepts $message as an argument and curl will create the notification:
function sendMessage($message){    $content = array(      "en" => $message      );    $fields = array(      'app_id' => "cxxxbca5-xxxx-4e54-xxxx-ca07exxxx013",      'included_segments' => array('All'),      'contents' => $content    );    $fields = json_encode($fields);    $ch = curl_init();    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',                      'Authorization: Basic MmFhMDkxN2ItYTRjOC00OTg1LWJmZjItY2JhYTY4Y2RjMTQx'));    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);    curl_setopt($ch, CURLOPT_HEADER, FALSE);    curl_setopt($ch, CURLOPT_POST, TRUE);    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    $response = curl_exec($ch);    curl_close($ch);    return $response;  } Now call this method in the trigger function of the Pusher. When Pusher sends the message, a notification will be created by the OneSignal API and send it to all subscribed users.  // Return the received message  if($pusher->trigger('test_channel', 'my_event', $data)) {   $response = sendMessage($data);   echo 'success';      } else {       echo 'error';  }
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Conclusion
The good thing is even when you are not online and the browser tab is also closed, you will still get chat notifications through the OneSignal push notification service. Here is the PHP chat application demo that highlights the push notification functionality.
Note: As there is no login method for the user at the moment, it will NOT authenticate the user, save or retrieve message history. I might add these features in a later version of the app.
Shahroze Nawaz
Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.