I'm trying to push new contents for a simple div
element on a web page (content consists of 2 iFrame
s). I've followed the online tutorials closely.
The setup is:
$_REQUEST
.div
. It has a JavaScript that sets up a listener to the PHP file.When the switcher button invokes the PHP file, the PHP file opens in a browser window and displays the text that I want the target window to receive. The listener in the target page doesn't appear to be getting the message. (I have the text/event-stream
and no-cache headers
defined.)
This is a very minimal app and closely follows the tutorials. The pages are being served by apache2 and PHP 7 on a Raspberry Pi. I have the feeling I'm missing something simple.
In index.html
, which is supposed to replace the contents of a div
with the received text:
<div id="serverData"> ...(2 iframes)... </div>
...
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("ViewController.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
In ViewController.php
, the source of the update:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//stream new webpages to the main view
$myPDO = new PDO('sqlite:/home/pi/pi_DB');
if (isset($_REQUEST['pageNo']) ) {
$result = $myPDO->query("SELECT htmlContent FROM views WHERE pageID = " . $_REQUEST['pageNo']);
$queryResult = $result->fetch(PDO::FETCH_ASSOC);
echo "event: message
"; // same result with or without this line
echo "data: " . $queryResult['htmlContent'] . "
";
flush();
}
In viewswitcher.html
which has the buttons to select different contents:
<p>
<button class="button" onclick="swapViewIntoIndex(2)">Select View 2</button>
</p>
<script>
function swapViewIntoIndex(viewNumber) {
// load ViewController.php and pass it the button (view) number
switch (viewNumber) {
case 1:
var url = 'ViewController.php?pageNo=1';
window.location.href = url;
break;
case 2:
var url = 'ViewController.php?pageNo=2';
window.location.href = url;
break;
default:
}
}