2

I try to use server side event with updating or adding data in database. In this case, why the onmessage event in index.html doesn't work after I add data to database by dataAdd.php?

index.html :

<body>  
    <div id="result"></div> 
</body>  
<script>  
    var result = document.getElementById("result")l
    if(typeof(EventSource) !== "undefined") {  
        var source = new EventSource("sse.php");  
        source.onmessage = function(event) {  
            result.innerHTML += event.data + "<br>";  
        };  
    } else {  
        result.innerHTML = "Sorry, your browser does not support sse";  
    }  
</script>

sse.php :

<?php 
    header('Content-Type: text/event-stream');  
    header('Cache-Control: no-cache');  
    mysql_connect("localhost","username","password");  
    mysql_select_db("database");  
    mysql_query("set names utf8");  
    $result = mysql_query("select * from table order by id desc limit 1;");  
    $row = mysql_fetch_array($result);  
    echo "data: $row[message]";  
    flush();  
?>

dataAdd.php :

<?php  
    mysql_connect("localhost","username","password");  
    mysql_select_db("database");  
    mysql_query("set names utf8");  
    if(isset($_GET['text'])) {  
        mysql_query("insert into chat (message) values ('$_GET[text]')");  
    }  
?>
Charnstyle
  • 93
  • 7
  • 2
    **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Jan 31 '16 at 22:00
  • 1
    Your message is missing the two new lines that terminates it (and separates it from the next message) – Quentin Jan 31 '16 at 22:02
  • You are sending a message when the connection is initially made and then stopping. You haven't written any code to send another message when the data changes. You should probably read [a tutorial](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events). – Quentin Jan 31 '16 at 22:03
  • I would like to see some example of code. – Charnstyle Feb 01 '16 at 03:09
  • There's an example of code in the tutorial I linked to. – Quentin Feb 01 '16 at 09:04

0 Answers0