1

Hi I'm currently working on a personal project which has two components. I want to POST "baby, 1" to my server, and when my server receives that "baby, 1", I want to change the webpage to reflect the date (currently using the date to test). I'm currently using Postman to test and largely borrowing code from W3Schools.

testpage.php

<html lang ="en">
<head>
    <meta charset ="UTF-8">
    <title>Title</title>
</head>
<body>
<div id = "result"></div>


<script>
    if (typeof(EventSource) !== "undefined")
    {
        var source = new EventSource("server.php");
        document.getElementById("result").innerHTML+="thug";
        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...";
    }
</script>

</body>

</html>

server.php

<?php

$bool = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!empty($_POST["baby"])) {
        $bool = $_POST["baby"];
        if ($bool == 1) {

            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');

            $time = date('r');
            echo "data: The server time is: {$time}\n\n";
            flush();

        }
    } 
}

?>

When I test with the w3schools default code

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

testpage.php updates properly. When I try to POST to server.php with (baby,1) testpage.php does not update. I am really struggling to figure out why this is happening.

Aire
  • 127
  • 2
  • 11
  • What is the use of all the ifs in server.php? I don't see you using it in your client code. Also, I believe server sent events uses *GET requests* but you only respond to *POST requests*. – E. Sundin Feb 11 '17 at 06:46
  • @E.Sundin I'm just checking if the value being sent is 1. What do you mean by server side events uses GET requests? – Aire Feb 11 '17 at 06:52
  • http://stackoverflow.com/questions/12431665/post-to-php-with-server-sent-events – mplungjan Feb 11 '17 at 06:52
  • Also have a look at a better resource: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events – mplungjan Feb 11 '17 at 06:52
  • @mplungjan What do you think would be the best way to tackle my problem? I feel like SSEs are meant for constant messaging from the server, but I want the server to wait for the post and I want the webpage to wait for the server. – Aire Feb 11 '17 at 06:56
  • Where is `POST` request made to server? – guest271314 Feb 11 '17 at 07:05
  • 1
    It seems to me your use case is not lending itself to server sent events at all. – mplungjan Feb 11 '17 at 07:06

0 Answers0