It is the first time in years I'm posting a question to any community. I've been working with PHP/SQL for years so far and during this time i never had to deal with JavaScript.
So maybe you can provide me with some help cause i tried everything already without solving this problem.
The script below is currently working properly in a PHP powered website. In the event stream I'm posting updates read by dyntasks.php from a text file on the filesystem updated by the app engine
?><script type="text/javascript">
if(typeof(EventSource)!=="undefined") {
var eSource = new EventSource("dyntasks.php");
eSource.onmessage = function(event, previous) {
//if ( (previous !== event.data) ) {location.reload(true);};
document.getElementById("serverData").innerHTML = event.data;
};
} else { document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events."; }
</script><?php
The script updates a block on the page and it is working properly.
The block is showing text in this form:
2017-03-21 16:08:15: task 21624 completed
2017-03-21 16:11:08: task 21627 completed
2017-03-21 16:36:01: task 21629 completed
2017-03-21 17:52:08: task 21635 completed
updating...
Now I need to UPDATE THE WHOLE PAGE when a specific task id is completed. The "taskid" is already stored in a variable and it is also available in the querystring.
/index.php?id=taskmanager&fullpage=21624
I tried for like 20 hours to update the JavaScript code but i couldn't make it to arrange it in such a way that it can trigger the
location.reload(true)
Can you please provide me with some hint? I think i only need to know how to save the event.data variable into a global variable to be used before the function to trigger the update but any further advice will be appreciated.
One way you can do it is by change the event stream from strings to message objects.
Instead of sending:
echo "2017-03-21 16:08:15: task 21624 completed";
You can do:
echo json_encode(array(
"action" => "task completed",
"task id" => 21624,
"ts" => "2017-03-21 16:08:15"
));
Then in JavaScript you can do:
eSource.onmessage = function(event) {
event = JSON.parse(event);
if (event.action === "task complete") {
document.location.href = "/index.php?id=taskmanager&fullpage=" + event["task id"];
}
};