I'm having a bit of a nightmare here, so any help would be gratefully appreciated! Firstly, I'll explain what I'm trying to do:
I'm trying to implement a system like described here: https://mcmap.net/q/107917/-how-does-facebook-gmail-send-the-real-time-notification on my localhost MAMP server using Yii framework. I have a function that checks if there are any new notifications in the DB - if so, it parses them and json encodes them. I have this function called on a while loop every 5 secs.
So: going to /user/unreadNotifications triggers the following
Yii::log('test'); // to check it's getting called
$this->layout=false;
header('Content-Type: application/json');
// LONG POLLING
while (Yii::app()->user->getNotifications() == null) {
sleep(5);
}
echo Yii::app()->user->getNotifications(); // prints out json if new notification
Yii::app()->end();
return;
This works fine - gone to the link in browser and verified json response - all good.
I have then tried all sorts of jQuery stuff to get it working... The ONLY way I have found to work is using $.ajax
with type POST but ONLY when there is a waiting notification (so some json is returned). $.get
or $.post
gets "aborted" (displayed in firebug) but the URL is called (because I can see the log file is updated) - odd.
My original setup using $.get
is:
<script type="text/javascript">
function notificationPoll() {
$.get('<?php echo Yii::app()->createUrl('user/unreadNotifications') ?>','', function(result) {
$.each(result.events, function(events) {
alert('New Notification!');
});
notificationPoll();
}, 'json');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
timeout: 60 //set a global ajax timeout of a minute
});
notificationPoll();
});
</script>
This just gets "aborted" for some reason. I've tried with 'jsonp' even though it is not a CORS request.. but that doesn't work either.
Can't seem to get anywhere with this! Can anyone chip in?
Many thanks