POST for PHP with events sent by the server?

Is it possible to use SSE to send POST data to PHP, for example, in Ajax?

I have been using AJAX with poor results in long polling methods for a long time. I also thought about WebSockets, but it seems a little redundant.

+4
source share
2 answers

No, SSE cannot send any data to the server.

You can still use SSE to read real-time data and use AJAX to load any data (you may need a common database for transferring information between AJAX receiving processes and sending SSEs).

+4
source

You can send data via GET.

eg.

name=john&name=lea 

This is a simple script that sends the server iteration number and the server returns the move using SSE.

This project consists of two files (index.php and ssedemo.php).

index.php contains a text box and a button. the text field should contain the number of loop iterations in ssedemo.php

  <h2>Server Sent Event Test</h2> <form> <label>Process Duration</label> <input type="text" id="progVal"> <input type="button" value="Get Messages" onclick="updateProgress()"/> </form> <div id="container"> </div> 

Updateprogress

  function updateProgress() { var input = $('#progVal').val(); var evtSource = new EventSource("ssedemo.php?duration=" + encodeURIComponent(input)); evtSource.addEventListener("progress", function (e) { var obj = JSON.parse(e.data); $('#container').html(obj.progress); if( parseInt(obj.progress) == 100){ evtSource.close(); } }, false); } 

this function gets the contents of the text field using jQuery and then creates an eventSource . The EventSource () constructor takes one or two arguments. The first indicates the URL to connect to. The second indicates the parameters, if any, in the form of an EventSourceInit dictionary.

You can pass what you want by adding it to the URL, as in GET.

"ssedemo.php?duration=" + encodeURIComponent(input)

On the server side, you should set the header type and disable the cache as recommended by W3C

 header("Content-Type: text/event-stream"); header("Cache-Control: no-cache"); 

then you will get the data using $ _GET, as usual.

 $TotalNo = $_GET['duration']; for ($i = 1; $i <= $TotalNo; $i++) { updateProgress($i, $TotalNo); sleep(1); } function updateProgress($currentVal, $totalNo) { $completionPrecentage = $currentVal / $totalNo * 100; echo "event: progress\n"; echo 'data: {"progress": "' . $completionPrecentage . '"}'; echo "\n\n"; ob_flush(); flush(); } 

if you want to send an array you can refer to this

0
source

Source: https://habr.com/ru/post/1434297/


All Articles