6

Is it possible to use SSE to send POST data to PHP like in Ajax?

I've been using AJAX now for quite a while with bad results in long-polling technicues. I have also been thinking about WebSockets, but it seems a bit redundant.

Paul R
  • 208,748
  • 37
  • 389
  • 560
user1431627
  • 815
  • 3
  • 13
  • 30
  • 1
    SSE is designed for one-way push, not two way communication - for this Web Sockets could be more appropriate – tomfumb Sep 14 '12 at 20:40
  • how about node.js, http://nodejs.org – FirmView Sep 14 '12 at 20:40
  • @tomfumb I only POST 2 bytes of data – user1431627 Sep 14 '12 at 20:49
  • that's irrelevant; to my knowledge (limited by the fact that SSE is not well documented) the only communication allowed from the client to the server is in initiating the connection. Once the link is established (or re-established in case of failure) data only flows one way. – tomfumb Sep 14 '12 at 21:18
  • also see a question I once asked highlighting PHP's inadequacy with SSE: http://stackoverflow.com/questions/9070995/html5-server-sent-events-prototyping-ambiguous-error-and-repeated-polling – tomfumb Sep 14 '12 at 21:41
  • @tomfumb so there's no other way other than ajax and websockets? I send so little informataion and my ajax request does take 171 bytes and that's a lot when sending such little information. – user1431627 Sep 15 '12 at 16:39
  • Even if your user is in Northern Alaska on a 28K modem connection 171 bytes travels in the blink of an eye: why so concerned? Unless you're communicating with the Mars Rover this level of micro-optimisation is almost certainly unnecessary – tomfumb Sep 17 '12 at 20:28
  • @tomfumb It does matter when my requests are slower than everyone elses! – user1431627 Sep 20 '12 at 06:53
  • Sorry, I'm abandoning this discussion. I suggest you invest your time and efforts in parts of the application that users actually care about (e.g. usability) and forget micro-optimisation. Maybe look at http://www.calctool.org/CALC/prof/computing/transfer_time and see how much time you're trying to save – tomfumb Sep 20 '12 at 21:01

3 Answers3

6

No, SSE cannot send any data to the server.

You can still use SSE to read data in real time and use AJAX to upload any data (you might need a shared database to pass information between AJAX-receiving processes and SSE-sending one).

Kornel
  • 97,764
  • 37
  • 219
  • 309
0

You can send data via GET.

e.g.

name=john&name=lea

This is a simple script that sends to server number of iteration and the server return progress using SSE.

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

index.php contain a text box and a button. the textbox suppose to contain the number of iteration of the loop 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 get the content of the textbox using jQuery and then create an eventSource. The EventSource() constructor takes one or two arguments. The first specifies the URL to which to connect. The second specifies the settings, if any, in the form of an EventSourceInit dictionary.

You can pass what you want by adding it to URL as you do with GET.

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

In the server side, you have to set header type and disable cache according to W3C recommendation

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

then you 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 array you can refer to this

Community
  • 1
  • 1
0

The EventSource API does not support POST method, however that does not mean that you cannot use SSE with POST. You just cannot use the EventSource API. There are alternative implementations however. One example is sse.js which allows you to specify a payload, and also headers if you need. sse.js should be a drop-in replacement for EventSource, eg:

var source = new SSE("get_message.php");
source.onmessage=function(event)
{
    document.getElementById("message-window").innerHTML+=event.data + "<br>";
};

In order to use a POST method, you just need to specify a payload, eg:

var source = new SSE("get_message.php", {payload: 'Hello World'});

And, since it is a fully compatible polyfill, you can probably do this:

EventSource = SSE;
var source = new EventSource("get_message.php", {payload: 'Hello World'});
source.onmessage=function(event)
{
    document.getElementById("message-window").innerHTML+=event.data + "<br>";
};
Ns789
  • 531
  • 10
  • 21