I am trying to use server sent event to get information from the database and update on my html page, immediately a new message enters, these are my codes
function update()
{
if(typeof(EventSource) !="undefined")
{
var source=new EventSource("update.php");
source.onmessage=function(event)
{
$scope.my_messages=JSON.parse(event.data)
}
}
}
update();
<div ng-repeat="x in my_messages">
<div>{{x.sender_username}}</div>
<div>{{x.title}}</div>
<p>{{x.messages}}</p>
</div>
at the update.php,I have this
<?php
include 'first.php';
$newUser= new Participant();
$newUser->connect();
$newUser->call_new_message();
?>
At first.php, I have this
public function call_new_message()
{
$sender=$_SESSION['username'];
$receiver=$_SESSION['receiverUsername'];
$a = mysqli_query($this->con, "SELECT * from messages_tb WHERE sender_username= '$sender' and receiver_username='$receiver' ");
if ($a) {
$s=$a->fetch_all(MYSQLI_ASSOC);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo"data:".json_encode($s)."
";
flush();
// echo json_encode($s);
}
else{
echo "An error occurred";
}
}
It worked well except that I expected it to update data in the divs in the html page immediately a new message comes in the messages_tb but it's not working like that, I have to refresh the page before I can get the new message in the div. Please, help out. thanks
</div>