0

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)."\n\n";

 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

atomty
  • 187
  • 2
  • 16
  • Please read up on [preventing SQL injection](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – danblack Sep 16 '18 at 00:57
  • thanks alot, I really appreciate your contribution. Please can you help provide answer to my initial question – atomty Sep 16 '18 at 07:33

1 Answers1

0

I guess adding $scope.$apply() in on scope().message handler should work for you.

source.onmessage=function(event)
    {
      $scope.my_messages=JSON.parse(event.data);
      $scope.$apply();
    }

Reason is, angular might not be aware of plain java script updating the data. so forcefully you can tell angular to update the scope.

Naveen Kumar G C
  • 1,332
  • 1
  • 10
  • 12