I have a little nightmare here, so any help would be greatly appreciated! First, I will explain what I am trying to do:
I am trying to implement the system described here: https://stackoverflow.com/a/166268/2126 on my localhost MAMP server using the Yii framework. I have a function that checks if there are any new notifications in the database - if so, then they analyze them, and json encodes them. I have this function called in a while loop every 5 seconds.
So: going to / user / unreadNotifications starts the following
Yii::log('test'); // to check it 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 - went to the link in the browser and confirmed the json answer - all is well.
Then I tried all kinds of jQuery things to make it work ... ONLY, as I found, works with $.ajax with a POST type, but ONLY when there is a notification about the wait (so some json returns), $.get or $.post gets "interrupted" (displayed in firebug), but the url is called (because I see that the log file is updated) - odd.
My initial setup with $.get :
<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>
For some reason, it's just "interrupted." I tried using "jsonp", although this is not a CORS request .. but this does not work either.
It seems itβs not going anywhere! Can anyone chip?
Many thanks
json jquery ajax php getjson
cud_programmer
source share