0

In a HTML5 website i'm building, NOT AN APP for a mobile phone, i implemented a chat box system. Users write a message and then using AJAX the page loads a div with the message. The messages are stored in a mysql database and sorted in order DESC to be shown.

I checked in https://stackoverflow.com/ and seen solution for apps in Ruby or PHP (using Comet, socket.io, Sinatra and some other approaches on top of NODE.JS), but that is not what i want.

I want to use plain PHP and Javascript notification to display notifications every time chat users submit a message.

The problem is that the notification works but only appears in the machine of the user who write the message. Other users that have the browser open (Chrome) and in the tab with the chat system doesn't see the notification because it doesn't show up.

My Question and problem is this one: Is it possible to make the notification appear in all the host's who are browsing in the chat box system?

Here is my JAVASCRIPT code for grabbing the user messages and display them in a HTML div. The toast notification JS appearing at the bottom is commented and disabled so it doesn't count for what i wanna do.

function submitChat(){
    if(form1.uname.value == '' || form1.msg.value == ''){
        alert('Todos os campos são necessários.');
        return;
    }
    var uname = form1.uname.value;
    var msg = form1.msg.value;
    var xmlhttp = new XMLHttpRequest();

// HTML5 notification API

function showNotification() {
    var notification = new Notification(uname1.value + ' ' + 'diz:', {
        dir: "auto",
        lang: "",
        body: msg1.value,
        tag: "sometag",
    });
    setTimeout(function() {
        notification.close();
    }, '3000');

    // notification.onclose = …
    // notification.onshow = …
    // notification.onerror = …
}
// document.querySelector("#submeter").onclick = showNotification;

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
        // chama a função de notificação
        showNotification();
        // após submit limpa o campo da mensagem
        form1.msg.value = '';
    }
}
xmlhttp.open('GET', 'insert.php?uname='+uname+'&msg='+msg, true);
xmlhttp.send();
}

/* JQUERY */
$(document).ready(function(e){
    $.ajaxSetup({cache:false});
    setInterval(function() {$('#chatlogs').load('logs.php');}, 500);

    /* toast notification system */
    /* web/toast */
    /* configurar CSS e JS folders em AppAsset.php */
    /*
    $('#submeter').click(function(s){
        $.toast({
            text: msg1.value,
            heading: uname1.value,
            position: 'top-right',
            icon: 'success',
            showHideTransition: 'plain',
            bgColor: '#5cb85c',
            textColor: '#000'
        });
    });
    */
});

Here is the HTML5 part:

<body>
<h3>Chat Room</h3>
<br/>
<form name="form1" id="form1">

    <div class="col-xs-12">
        <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">Username:</span>
            <input type="text" class="form-control" aria-describedby="basic-addon1" placeholder="" id="uname1" name="uname" readonly value="<?= Yii::$app->user->identity->username; ?>">
        </div>
    </div>

    <br/><br/><br/>

    <div class="col-xs-12">
        <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">Mensagem:</span>
            <textarea class="form-control" rows="3" name="msg" id="msg1"></textarea>
        </div>
    </div>

    <br/><br/><br/><br/><br/>

    <a href="#" onclick="submitChat()" class="btn-sm btn-success" id="submeter">Enviar</a><br/><br/>

    <div id="chatlogs">
        A carregar... Por favor espere...
    </div>

</form>
</body>

Here is the PHP part:

<?php
$con = new mysqli("localhost","root","root","efansredes");
$results=$con->query("SELECT * FROM chat ORDER by id DESC");

$i = 0;

while($row=$results->fetch_array()){
    if($i %2 == 0)
    {
      $class = 'even';
    }
    else
    {
      $class = 'odd';
    }
    $i++;

// output da tabela
echo '<div class="alert alert-success" role="alert">';
echo "<table>";
echo "<tr class='$class'>";
echo "<td>"."<b>".$row["username"]."</b>".": ".$row["msg"]."</td>";
echo "</tr>";
echo "</table>";
echo "</div>";
}

?>
Community
  • 1
  • 1
André Castro
  • 1,527
  • 6
  • 33
  • 60
  • 1
    It's a bad idea to do it with PHP because you do not have any real-time by default. That means you would have to automatically refresh your client to request the latest DB-Entries from your PHP-Backend. Maybe this can help you tho: [Socket.io in PHP](https://github.com/walkor/phpsocket.io) – Noshii Jun 06 '16 at 09:48
  • Ok. I will give it a try and then post the results. Many thanks. – André Castro Jun 06 '16 at 09:54

1 Answers1

0

Note that you're not checking if there are notifications.

showNotification();

You're just calling the function to show notifications after the user sends a message to the server. In this case you'd need to make long polling trick with Ajax request that waits for a notification and anything you want. In the PHP of the long polling you'd check in chat database if there are unread messages – case yes, the long polling can stop with some data in echo, if you prefer, it can echo the message data.

Then, you must have a method to know the unread messages. Suppose you'll discover the unread messages by the last ID you captured from a last message in the chat – then, in database, only get messages by bigger ID than the others. Then you can count how many rows of messages you got. If the couting number is bigger than 0, then the long polling must stop (with or without results).

When the long polling stops (or give response), the XMLHttpRequest ends – and when it ends is because there are unread messages. Then you can do something there.

Though, if you have a server where you have a complete shell, you shouldn't use Ajax, but WebSockets.

Community
  • 1
  • 1