Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass POST parameters with HTML SSE?

I've got a block of code here that uses HTML 5 SSE - the EventSource object, which lets a php script push updates to the webpage. However, I'm interested in also passing parameters to the script. How can I do that?

Here's the code:

if(typeof(EventSource) !== "undefined")
    {
        var source = new EventSource("get_message.php");
        source.onmessage=function(event)
        {
            document.getElementById("message-window").innerHTML+=event.data + "<br>";
        };
    }
else
    {   
        document.getElementById("message-window").innerHTML="Sorry, your browser does not support server-sent events...";
     }

The closest thing I can think of is to use AJAX, as in

$.post("get_message.php", {largest_id: 30}, function(data, status){ some function });

However, I'm not sure how to write the jQuery for this?

like image 255
blazonix Avatar asked May 23 '14 09:05

blazonix


1 Answers

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>";
};
like image 79
mjs Avatar answered Oct 14 '22 01:10

mjs