S
S
Silverviql2018-07-11 09:40:54
Yii
Silverviql, 2018-07-11 09:40:54

How to call a function from an included js file when conditions are met in a php file script on yii2?

Perhaps I phrased the question incorrectly. I have websocket server and client connected.
On the index page, I have implemented a client .

<button onclick="send();">Send</button>

<h1>Пример работы с WebSocket</h1>
<form action="" name="messages">
    <div class="row">Имя: <input type="text" name="fname"></div>
    <div class="row">Текст: <input type="text" name="msg"></div>
    <div class="row"><input type="submit" value="Поехали"></div>
</form>
<div id="status"></div>
<?php

echo <<<JS

<script>
    window.onload = function () {
        /*var socket = new WebSocket("ws://echo.websocket.org");*/
        var socket = new WebSocket("ws://localhost:8080");
        var status = document.querySelector("#status");
        console.log(socket)

        socket.onopen = function () {
            status.innerHTML = "cоединение установлено<br>";
        };

        socket.onclose = function (event) {
            if (event.wasClean) {
                status.innerHTML = 'cоединение закрыто';
            } else {
                status.innerHTML = 'соединения как-то закрыто';
            }
            status.innerHTML += '<br>код: ' + event.code + ' причина: ' + event.reason;
        };

        socket.onmessage = function (event) {
            let message = JSON.parse(event.data);
            status.innerHTML += `пришли данные:`+'<b>'+ message.name +'</b>'+  ':'+ message.msg + '<br>';
            if(message.msg!=0){
                 return['class' => 'strRebTabl'];
            }
        };
        
        
        socket.onerror = function (event) {
            status.innerHTML = "ошибка " + event.message;
        };
        document.forms["messages"].onsubmit = function () {
            let message = {
                name: this.fname.value,
                msg: this.msg.value
            }
            socket.send(JSON.stringify(message));
            return false;
        }
    }
    </script>
JS;
?>

Server:
<?php

namespace frontend\components;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class SocketServer implements MessageComponentInterface
{
    protected $clients;
    public function __construct()
    {
        $this->clients = new \SplObjectStorage; // Для хранения технической информации об присоединившихся клиентах используется технология SplObjectStorage, встроенная в PHP
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    /*public function onMessage(ConnectionInterface $from, $msg)
    {
        $data = json_decode($msg, true); //для приема сообщений в формате json
        if (is_null($data))
        {
            echo "invalid data\n";
            return $from->close();
        }
        echo $from->resourceId."\n";//id, присвоенное подключившемуся клиенту
    }*/
    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connections' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
           /* if ($from !== $client) {*/
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            /*}*/
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

I want to call the update function (from the included script.js file) of the gridview tables when one of the clients sends a message. From the beginning, every 3 seconds the tables were updated for me. Now the task is to update the tables only when one of the users has made some action or change, so I want to send messages via the web socket from the client who made the change and those who are connected run the script to update the gridview tables. Thanks for the answer.
function startRebTabl{
        $pjaxContainers = ['#10-pjax', '#11-pjax', '#12-pjax'];

        $.each($pjaxContainers , function(index, container) {
            if (index+1 < $pjaxContainers.length) {
                $(container).one('pjax:end', function (xhr, options) {
                    $.pjax.reload({container: $pjaxContainers[index+1]}) ;
                });
            }
        });

        $.pjax.reload({container: $pjaxContainers[0]}) ;

    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-07-11
@webinar

You return json from the server in which the name of the desired function, call the function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question