Answer the question
In order to leave comments, you need to log in
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;
?>
<?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();
}
}
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
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 questionAsk a Question
731 491 924 answers to any question