D4V1D
D4V1D

Reputation: 5849

Retrieve data from server with SSE named something else than "data:"

So I'm writing this basic custom jQuery plugin that would handle animating progress bars based on Server-Sent Events (as for now: I plan on handling Websocket and Long-Polling Ajax too).

I'm willing to know if there is any way for the data sent by the server to be named differently. Up until now, I have read that the server must output something like:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
for($i = 0; $i < 100; $i++) {
    echo 'data:'.$i."\n\n"; // must be data: and not something else!
    flush();
    sleep(1);
}

So it can be retrieved using

var stream = new EventSource('/api');
stream.onmessage = function(e) {
     console.log(e.data); // outputs $i as it is sent by server every second
}

Therefore, I'm wondering is the data sent by server has to be named data: for it to be read client-side or can it have another name? (and then read it client-side with e.anotherName). I would like not to go towards creating a JSON object server-side as it would greatly complicate manually setting up this plugin.

The purpose behind all this is, in order to make the progress bar to progress, I need a percentage that can only be calculated by having the maximum value of $i server-side and the current value. If you can think of another way to have this percentage without outputting the total through the first event, I'm also willing to know.

Thanks.

Upvotes: 0

Views: 196

Answers (1)

WebTech
WebTech

Reputation: 11

'data:' is compulsory for SSE but it also support for 'id' and 'event' which may help you in your case, check this link

Upvotes: 1

Related Questions