I have a forum (in PHP with Symfony2 framework) and I want something really close to real time notifications. What I want more specifically is that when a user receives a private message, a notification appears. I've tried to use the long polling technique, but I have a problem.
So, I send an ajax call from javascrip to php. PHP receives it and makes a query to database to see if there are any new notifications for the user requested by the ajax. If it finds something, it returns that result, else sleeps x seconds. This is happening in a while(true) condition. The problem is that if it doesn't find something, it sleeps, then searches again, and again it sleeps and so on, and while this happens nothing else works. If I try to reload the page, click on something from the forum, read a topic, and so on, all are blocked waiting for that ajax call to finish. What can I do to make that ajax call run in parallel with everything else, or unblock the server while the ajax isn't finished.
This is what I have in javascript:
function poll() {
$.ajax({
type: "post",
url: url to the action from controller,
async: true,
data: { 'userId': $('#userId').attr('data-value') },
dataType: "json",
success: function(result) {
call method to display the notification(s) to the user
setTimeout(poll, 5000);
}
});
};
$(document).ready(function(){
poll();
});
And here is the action from Symfony2 controller:
public function checkForNewNotificationsAction($userId) {
while (true) {
/** @var \Forum\CoreBundle\Entity\Notification[] $notifications */
$notifications = query the database
if ($notifications != null) {
return new JsonResponse($notifications);
} else {
sleep(5);
}
}
}
I have also tried to call a regular PHP file with "pure" PHP code thinking that the action from controller and how Symfony2 manages the controllers is blocking my other activities, but it does exactly the same.
I'm trying to not use any other "tools" like Node.js with Socket.io or something like this because I never worked with them and really don't have time to study. The project must be done in a few days, and still have a lot to do. Also I'm trying to avoid simple ajax calls every x seconds, leaving this as my last option.