What would be the ideal mechanism to get notifications like in Facebook in to a dashboard ?. I am thinking the best way is to do a Ajax call to a php page every 5 seconds and retrieve the notifications.
Is there any better way to do a similar change?
It should work in all mobile browsers too.
I am doing it the following way,
use $.post
in jquery for get data without page refreshing.
$.post("page.php",{"act":1},function(data){
$("#id").html(data);
});
in page.php write your query
EDIT 1
I wrote a function like this after referring to some online notes and its working in realtime.
var TimeStamp = null;
function waitForMsg() {
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + TimeStamp,
async: true,
cache: false,
timeout: 50000, /* Timeout in ms */
// data: "TimeStamp=" + TimeStamp,
success: function( data ) {
var json = eval('(' + data + ')');
if ( json['msg'] != "" ) {
alert( json['msg'] );
}
TimeStamp = json['timestamp'];
setTimeout(
'waitForMsg()', /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
alert("error:" + textStatus + "(" + errorThrown + ")");
setTimeout(
'waitForMsg()', /* Try again after.. */
"15000"); /* milliseconds (15seconds) */
},
});
}
;
// calling after dom is ready
$(document).ready(function() {
waitForMsg();
});
PHP file is,
<?php
$filename = dirname(__FILE__).'/data.txt';
$lastmodif = isset( $_GET['timestamp'] ) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime( $filename );
while ( $currentmodif <= $lastmodif ) {
usleep( 10000 );
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$response['msg'] = file_get_contents( $filename );
$response['timestamp'] = $currentmodif;
echo json_encode($response);
EDIT 2
All work well but when there is no changed happend to data.txt file i get a error message like this in 50 seconds.
error:timeout(timeout)
how can this be prevented ?
REF : Javascript Variable Scope
From what I know, there are basically two ways to do this: polling, and websockets. Polling is either making many requests at an interval, or having a very long request the browser and server know is long (also called long polling). Then there is websockets. I haven't been in PHP land in a while, but last I checked websockets weren't really supported there. It could have changed. In Node world socket.io is a great solution that uses websockets and long polling as a backup.
A quick search has found this for websockets and php: http://socketo.me/docs/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With