Load Chatbox message notifications

Asked

Viewed 82 times

0

Is there any way to refresh the page without the method setTimeout or setInterval directly by PHP? if you have by JS also serves.

Is that I’m making a system of notifications and chats that needs second to second to be bringing data from Chatbox message notifications straight from the server and the setInterval is giving a scolding and headaches.

1 answer

2


PHP is back-end, there is no way he can make such a direct interaction with the front-end.

You have two options:

Ajax + setTimeout

No reason not to want to use the setTimeout (he is your friend), an example of ajax with setTimeout:

html:

<div id="respostas"></div>

Js:

function Notificacoes() {
    var request = new XMLHttpRequest();
    request.open("GET", "test.html", true);//true é "assincrono"

    request.onreadystatechange = function (event) {
        if (request.readyState === 4) {
            var target = document.getElementById("respostas");
            var newItem = document.createElement("div");

            if (request.status === 200) {
                 newItem.innerHTML = request.responseText;
            } else {
                 newItem.innerHTML = "Erro na resposta: " + request.status;
            }

            //Adiciona nova mensagem do chat no corpo
            target.appendChild(newItem);

            setTimeout(Notificacoes, 500);//Espera 500ms pra fazer uma nova requisição
        }
    };
    request.send(null);
}

Notificacoes(); //Inicia o Ajax (recomendo window.onload ou $.ready do jQuery)

Another recommendation I make is to bring data json instead of html, because that is how it will be less server consumption and the response will take less. So with this json data you use javascript to generate HTML.

Using websockets

Webscokets are more complicated, however the advantage they exert is that the server sends the answer because the connection is constant:

js:

var socket = new WebSocket(host);

socket.onopen = function(msg) 
{ 
    if(this.readyState == 1)
    {
        console.log("conectado"); 
    }
};

//Recebe os dados do socket
socket.onmessage = function(msg) 
{
    var target = document.getElementById("respostas");
    var newItem = document.createElement("div");

    newItem.innerHTML = msg.data;

    //Adiciona nova mensagem do chat no corpo
    target.appendChild(newItem);
};

socket.onclose = function(msg) 
{ 
    console.log("Desconectado " + this.readyState); 
};

socket.onerror = function()
{
    console.log("Erro");
};

php:

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);

PHP documentation:

Why not the setInterval

Unlike setTimeout setInterval does not wait for the process to finish, so if the ajax requests are long you may overload the browser.

  • Is there any way to make this code Ajax + setTimeout receive a type value <input type="text" user-de="1" user-para="2"> when you click on a type function.. <a href="#" onclick="openWidChat(1,2)">Eric</a> .. then he must take the value of user-de and user-para

  • @If possible, since it is a server+client interface, it is possible to send data and receive using GET parameters, for example: request.open("GET", "test.php?action=receber&user-de=1&user-para=2", true);

  • I have already tried .... did not work out as I expected... is that it will receive a value that is not printed on the HTML page it will receive by clicking on the link... When he clicks on the link he has openWidChat(1,2) these values are played in the INPUT as user-de="1" user-para="2" that had not in the structure ater click on the link, Dae these values should be played within the structure of Notifications(),... until then I managed to do this, but when procimo refresh in <div id="answers"></div> the values gets 'NULL' and ends up losing the values of INPUT. Understands?

  • It’s not that it didn’t work, but it seems to me that you didn’t know how to create logic. With the forgiveness of the word, but this is another @Pedroquezado issue. I recommend you create a new question and add details of your code and how it works to be able to answer.

  • would you have time to help me on this roll? @Guilhermenascimento

  • On Sunday maybe @Pedroquezado but you can formulate a new question with details of your current code and functioning so that it is possible to answer, I believe there is enough user with as much ability as I to answer and will help you maybe today :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.