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?

Answers:

Answer

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>";
};
Answer

@blazonix you must differentiate between sending and receiving when using SSE.

EventSource is meant only for receiving data from server. To send data to server you must use regular AJAX request.

In my library I'm making it possible to reuse the same path for sending and receiving but I'm distinguishing what the caller wants to do based on Accept header:

  • Accept: text/event-stream - it is a browser and wants to initiate event stream connection
  • Accept: any other type - it is a regular non/AJAX call GET or POST

Sample java code: GitHub

Answer

That is so simple.

$.post('your_url.php?your_parametre1=' + your_value1 + '&your_parametre2_likewise=' + your_value, function(data) {
alert(data); // whatever you echo from php file as a identifier of success or error.
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.