Advice for ajax message notifications? - php

I'm here to ask you if what I think is the right way to go around coding this.
I have a site that receives private messages and I wish a flag to show up the moment the person receives a message. Should I check for new messages every 3 seconds and show the flag if there is a new message or is there a better way?
If I did it in ajax, I was thinking check every 3-5 seconds for new messages, and once there's a flag, stop checking for more.
My only concern is, if it checks every 3-5 second, will it cause any lag or glitchyness for the person when they're typing? Lets say they're typing out a paragraph somewhere, I don't want their writing to glitch while it checks those 3-5 second intervals.
One of my coder friends mentioned there is a method with Ping(?) or something like that. Where the person is always connected to the server and when there's a change it notifies the user. I'm totally unsure of how this works.
Anyone know how facebook does it? haha.
Thank you!

If you have done the AJAX well, it should not lag/glitch while typing. Something like 3-5s is good as its fast enough but won't slow down server/browser.
Did he mean "push"? In push the messages are pushed to client in realtime, client is not asking if there is new messages. This is most likely the method Facebook is using.

One of my coder friends mentioned there is a method with Ping(?) or
something like that
To be honest I really don't like periodic refresh(polling at intervals), because tt has scaling problems(I got notice from hosting provider when using periodic refresh). You should use more efficient transports like for example:
WebSocket
Adobe® Flash® Socket
AJAX long polling
AJAX multipart streaming
Forever Iframe
JSONP Polling(cross domain)
To use this you could for example use:
hosted solution pusher with API and generous free plan. This gives you max 20 concurrent and 100,000 messages per day, but no SSL, so do not transmit sensitive information over the wire. They also provide third-party PHP client available at github implementing REST API.
socket.io (I like this a lot)
tornado
netty
Anyone know how facebook does it? haha.
For chat they use Erlang. They also have open-sourced tornado(see link above) which they required from friendfeed which they acquired in the past. Facebook is a PHP-shop, but they decided to not use PHP for this, because PHP can not yet do this efficiently. Anyway they are using one of the efficients transports above.

Related

How to tell if someone has left

I was wondering how I could check if someone has left the site/page and perform an action after they left. I was reading on here and I found this:
No, there isn't. The best you can do is send an AJAX request every X seconds (perhaps only if the user moves the mouse). If the server doesn't receive any requests for 2X seconds, assume that the user left.
That's what I had planned for before but how could you make the server do something (in my case it's to remove them from the DB) if they stop sending the request? An example I can think of is how on Facebook when you go to the site you tell them you're here and online which marks you as online in chat but when you leave it marks you as offline. How is that possible?
Edit: After a while of using cron jobs I found out that web hosting sites don't like running cron jobs often enough to generate a "live" feelings on your site. So instead I found node.js and it works a 1000x better and is much simpler. I'd recommend anyone with the same issue to use it, it's very cheap to buy hosting for and it's simple to learn, if you know Javascript you can build in it no problem. Just be sure to know how Async works.
A not uncommon approach is to run a cron job periodically that checks the list of users, and does XYZ if they have been inactive for X minutes.
Facebook uses the XMPP protocol via the Jabber service to have a constant or real-time connection with the user. However, implementing one isn't an easy task at all. The most simple solution would be, as mentioned in the comments, to have the client make AJAX requests to the server every several seconds, so that the server may check whether the user is still viewing the site or not.
You might want to check out my question, which might be related to yours.
The only method I ever remember in my time developing is one that's not 100% reliable as a number of factors can actually and most likely cause it to either misfired, or not even run fully. Up to and including someone disabling JavaScript. Which grant it isn't highly likely with the way websites of today are put together. But people have the option to turn it off, and then people who are acting maliciously tend to have it off as well.
Anyway, the method I have read about but never put much stock in is, the onunload() event. That you tie into something like the <body> tag.
Example:
<body onunload="myFunction()">
Where myFunction() is a bit of JavaScript to do whatever it is your seeking to have done.
Again not superbly reliable for many reasons, but I think in all it's the best you have with almost all client side languages.

JavaScript checking for new content such as notifications

I'll try and explain this as best I can. But basically on a website when you have some dynamic content such as messages, notifications, etc... You would want this information to be presented to the user as soon as the message arrived. Example a user is sent a new message show show a bubble with the count in the header of your website.
You see this stuff on nearly every single website these days and I'm unsure as to the best way to implement such a feature.
My initial idea was to write some ajax call and then wrap this in a setInterval call so it's requested every 30 or so seconds. The obvious problem here is that a) you have to wait 30 seconds for the request and b) you might be requesting the server hundreds of times in a day with no actual new content to ever display.
My second thought was to use EventListeners as they seem for more ideal as from what I understand they only do a request when the server tells it something. But I'm not 100% sure how to build something like this. Can anyone whip up a quick example or point to something that would serve as the basis for something like this?
So to clarify what I want to do:
When something new happens like sending a message or creating a notification this will send an event that the event listener picks up and updates something on the page either showing a small popup with the info or updating a bubble e.g. Messages (2)
I'll be using CakePHP and jQuery to implement this. So anything specific to this would be awesome... Hopefully someone can help me out.
Essentially I'm asking about EventListener vs setInterval and how it would work with ajax calls...
As suggested by Alex Ball, you should research about COMET programming techniques, and also look at the answers for this question Simple comet example using php and jquery. There isn't really a "simple" answer to implement an effective technique to what you are asking for but the most effective one is using an iframe. Using an iframe will allow you to have a persistent connection with the server (PHP side). Here you will be able to check for new messages (query for new messages) and if there is any, return your data. Your ajax call (success function) will the process this data and then do another post back to the server. If there is none then you would have to loop.
Again, effective COMET Programming techniques are not simple to implement.
Here are some useful examples though:
http://www.webreference.com/programming/javascript/rg30/index.html ,
http://www.zeitoun.net/articles/comet_and_php/start , setInerval wouldn't be effective for chat, maybe notifications.
COMET techniques are not specific to CakePHP.

jQuery server side push with ajax

I am in the middle of making a social network, and i want it to be as smooth as facebook.
Like if you look in a console and look at logging, it doesn't update all the time with ajax calls.
on my site i have to load: notifications(the number of new notifs and the notifs themselves), friend requests(same as notifications), online friends(if there are any online it will load the pictures of the online users.) thats 6 ajax calls that is loaded every 10 second. and this causes a huge bandwidth waste and server requests.
Therefore i thought, what if the SERVER told the CLIENT when there was a new update instead of the CLIENT asking the SERVER every 10 seconds.
i have googled this problem and read about ajax push, and a framework called comet.
i just can't seem to find any info on how to implement this on jQuery.
I looked briefly into Comet. It appears to be ambitious, experimental and won't run on just any old server.
As I understand it, Comet doesn't really push as such but does something called "long polling", which I won't try to describe here. The web already has several good texts on the subject.
Personally, I would stick with the current plan (conventional AJAX) but make one general purpose call with all the necessary data bundled into an object and JSON encoded. This will reduce 6 requests down to one (every 10 seconds).
You can box-clever by returning nulls within the returned object for information that hasn't changed thereby minimising the length of each response.
As far as I know, you must make significant modifications on your webserver to get this thing to work. Also, server side php is not really a good option.
Somebody had already asked something similar here: Using comet with PHP?
You can try socket.io on node.js too. It works great for real time communication
http://socket.io/

Push notification to the client browser

I'd like to create an application where when a Super user clicks a link the users should get a notification or rather a content like a pdf for them to access on the screen.
Use Case: When a teacher wants to share a PDF with his students he should be able to notify his students about the pdf available for download and a link has to be provided to do the same.
There are several ways you can accomplish this. The most supported way is through a technique called Comet or long-polling. Basically, the client sends a request to the server and the server doesn't send a response until some event happens. This gives the illusion that the server is pushing to the client.
There are other methods and technologies that actually allow pushing to the client instead of just simulating it (i.e. Web Sockets), but many browsers don't support them.
As you want to implement this in CakePHP (so I assume it's a web-based application), the user will have to have an 'active' page open in order to receive the push messages.
It's worth looking at the first two answers to this, but also just think about how other sites might achieve this. Sites like Facebook, BBC, Stackoverflow all use techniques to keep pages up to date.
I suspect Facebook just uses some AJAX that runs in a loop/timer to periodically pull updates in a way that would make it look like push. If the update request is often enough (short time period), it'll almost look realtime. If it's a long time period it'll look like a pull. Finding the right balance between up-to-dateness and browser/processor/network thrashing is the key.
The actual request shouldn't thrash the system, but the reply in some applications may be much bigger. In your case, the data in each direction is tiny, so you could make the request loop quite short.
Experiment!
Standard HTTP protocol doesn't allow push from server to client. You can emulate this by using for example AJAX requests with small interval.
Have a look at php-amqplib and RabbitMQ. Together they can help you implement AMQP (Advanced Message Queuing Protocol). Essentially your web page can be made to update by pushing a message to it.
[EDIT] I recently came across Pusher which I have implemented for a project. It is a HTML5 WebSocket powered realtime messaging service. It works really well and has a free bottom tier plan. It's also extremely simple to implement.
Check out node.js in combination with socket.io and express. Great starting point here

How to make fast, lightweight, economic online chat with PHP + JS + (MySQL?) + (AJAX?)

What way will be best to write online chat with js? If i would use AJAX and update information about users and messages every 5sec - HTTP requests and answers will make big traffic and requests will make high server load.
But how another? Sockets? But how..
You seem to have a problem with the server load, so I'll compare the relevant technologies.
Ajax polling:
This is the most straightforward. You do setTimeout loop every 5 seconds or so often to check for new chat messages or you set an iframe to reload. When you post a message, you also return new messages, and things shouldn't get out of order. The biggest drawback with this method is that you're unlikely to poll with a frequency corresponding to how often messages are posted. Either you'll poll too quickly, and you'll make a lot of extra requests, or you'll poll too slowly and you'll get chunks of messages at a time instead of getting them in a real-time-ish way. This is by far the easiest method though.
HTTP Push
This is the idea that the server should tell the client when there are new messages, rather than the client continually bothering the server asking if there are any new ones yet. Imagine the parent driving and kid asking "are we there yet?", you can just have the parent tell the kid when they get there.
There are a couple ways to both fake this and do it for real. WebSockets, which you mentioned, are actually creating a stream between the client and the server and sending data in real time. This is awesome, and for the 4 out of 10 users that have a browser that can do it, they'll be pretty psyched. Everyone else will have a broken page. Sorry. Maybe in a couple years.
You can also fake push tech with things like long-polling. The idea is that you ask the server if there are any new messages, and the server doesn't answer until a new message has appeared or some preset limit (30 seconds or so) has been reached. This keeps the number of requests to a minimum, while using known web technologies, so most browsers will work with it. You'll have a high connection concurrency, but they really aren't doing anything, so it should have too high a server cost.
I've used all of these before, but ended up going with long polling myself. You can find out more about how to actually do it here: How do I implement basic "Long Polling"?
You should chose sockets rather than AJAX Polling, However there isn't much around about how you can integrate socket based chats with MySQL.
I have done a few tests and have a basic example working here: https://github.com/andrefigueira/PHP-MySQL-Sockets-Chat
It makes use of Ratchet (http://socketo.me/) for the creation of the chat server in PHP.
And you can send chat messages to the DB by sending the server JSON with the information of who is chatting, (if of course you have user sessions)
There are a few ways that give the messages to the client immediately:
HTML5 Websockets
good because you can use them like real sockets
bad because only a few browsers support it
Endlessly-loading frame
good because every browser supports it
not so cool because you have to do AJAX requests for sending stuff
you can send commands to the client by embedding <script> tags in the content
the script gets executed immediately, too!
...
So, in conclusion, I would choose the second way.
The typical approach is to use long polling. Though better not do this in PHP (PHP will need one process for each connection thus drastically limiting the number of possible visitors to your site). Instead use node.js. It's perfect for chats.

Categories