D
D
Dimazsever2015-01-22 17:16:42
PHP
Dimazsever, 2015-01-22 17:16:42

How to get data from a database using SSE?

I recently read about the new HTML5 technology SSE (Server-Sent Events) - a technology that allows you to receive web page updates from the server in real time.
I can't figure out how to get data from the database.

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

Everything is correct in the JavaScript code. What is wrong in php script?
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include("config.php");
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if($mysqli->connect_errno){
exit("Не удалось подключиться к MySQL");
}
$mysqli->set_charset("utf8");
$res = $mysqli->query("SELECT `message` FROM `messages` ORDER BY `id` DESC LIMIT 1");
$row = $res->fetch_assoc();
echo "data: anekdot:{$row['message']}";
flush();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav, 2015-01-22
@hedint

It is not clear from the question - do you have problems with the withdrawal from the database, or with any withdrawal at all?
Here's an example I just tested and it works:
pastebin.com/hJ3NJywS - server side code.
jsfiddle.net/bztd26kL - client code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question