I have been searching on the net for a code that refreshes the chat <div>
every time a new message is received from the other chat user. I have read about setTimeout()
and setInterval()
however need more experienced developers advice and help.
The best example is this website. Unless you refresh the browser, you will not see the notification right away. I guess the best example is facebook. Whenever the Database is updated, the notification is popped up right away without refreshing the browser.
Here`s my code.
- $check_sql = ("SELECT time from messages where conversation_id = '".$con_id."' ");
- $check_query = mysqli_query($con, $check_sql) or die ("ERROR checking:".mysqli_error($con);
- while($row = mysqli_fetch_assoc($check_query){
- $current_time = date_default_timezone_get();
- $message_time_sent = $row['time'];
- $cal = $message_time_sent->diff($current_time);
- $ans = $cal->format("%D %H:%i:%s");
- sscanf($ans,"%d %d:%d:%d ", $day, $hr, $min, $sec);
-
- if (($day == 0) && ($hr == 0) && ($min == 0) && ($sec >0)){
- //do something here to get receive message automatically and notification....
- }
What I want to achieve:
- Facebook automatically receives messages without refreshing the browser. I hope it could be like this.
- Automatic pop up of notification without refreshing the browser which I think it is not really important, once we can figure out item 1, then the rest will be all good.
The tricky part about using setInteval()
the browser will keep refreshing the <div>
chat so when the user input a text to send, it will disappear everytime it refreshes. Please excuse my English....
So, is there a proper way of handling this....