How do I implement observer pattern on PHP + Javascript/jQuery? - php

Just like in SO, where one is answering a question, if somebody has answered said question, a notification will appear (via AJAX?). My only way of somewhat replicating this is by including a timeout on my script that fetches if there is an update every n seconds. Is there a way to do this using observer pattern on PHP + Javascript (w/ jQuery)?

you have to look at the ReverseAJAX or COMET methodologies.
As per wikipedia
Reverse Ajax refers to an Ajax design
pattern that uses long-lived HTTP
connections to enable low-latency
communication between a web server and
a browser. Basically it is a way of
sending data from client to server and
a mechanism for pushing server data
back to the browser.
EDIT:
i suggest you to implement the following approach, this is simple to implement. I take stackoverflow answering as an example.
After the answer page load complete. Initiate a AJAX request (Asynchronos, so it wont block the UI)
And it will look for any new updates on the server side (polling the DB to check if any new answers added)
And return the data only to browser, if there is an update. otherwise stay calm.
After returning the data to client, client should invoke the another AJAX request and wait for the updates.
Repeat step 2 to 4 for the rest of the page life time.
Hope this helps.

If you use timeouts to query the server for updates, it may still be considered a peculiar implementation of the Observer pattern. Unfortunately, it's not possible to do it the other way around. If the server finishes responding to the main HTTP request, the client just finishes "listening" to it. The only way to do this is to make an asynchronous request from the client.

Related

Update div, in mysql with php and ajax, without reloading by timmer

I have to update the state of a div, the thing is like this. On 2 computers, the same web page must be open, and I have to be able to change the state of a div in one and automatically update it in the other without having to reload, I think that Ajax alone is not enough, since I do not want to put one kind of timer that reloads the div s automatically, if not, when clicking on a button on computer A, it will update on counter B Obviously using mysql and php. It's possible?
You're right, AJAX alone isn't enough.
What really serves your purpose is WebSockets.
In short:
The WebSocket API is an advanced technology that makes it possible to
open a two-way interactive communication session between the user's
browser and a server. With this API, you can send messages to a server
and receive event-driven responses without having to poll the server
for a reply.
Of course, understanding how WebSocket works is mandatory, but it would be a waste of time to use the interface directly and deal with it (unless for learning purposes), so i suggest using Puhser JS Library for this purpose.
Now, here's the flow of the steps:
Get the free API keys of Pusher
Include the client channels library
Open a connection to channels
Subscribe to a channel
Listen for events
Trigger events from your server
I want to focus on steps 5 and 6:
You make an AJAX request from one page and this request is sent to the server, now instead of making the server responds directly you just trigger the responsible event for <div> element update, that what needs to happen in step 6.
Since all the browsers are subscribed to the responsible event and are listening, when step 6 trigger this event all browsers recieves it , at this step 5 you would perform DOM manipulation to update the <div> element.
I'm sorry if my explanation is bad, but don't worry because it's easier than it looks, the documentation explains it in an excellent way.

How to implement a push notification system on a website in PHP?

I would like to ask if someone knows how can I notify a user that looks at a page of my website with a push notification (i.e. make my server notify the user that there's something to him).
I understand the polling mechanism (I can implement it through a simple loop with a setInterval() in Javascript and pass a callback that makes an async XMLHttpRequest or a getJSON), but what about the push mechanism?
I guess I need to make a sort of a call with the server that should tell the client that it has something for him??? Assuming that my website is in PHP, is there a way to make it?
Thanks for the attention!
The network topology usually does not allow real push notifications. Certainly a browser won't. What you can do is using a special kind of polling strategy that comes close: "long polls".
Basically these are ajax based poll requests that are not immediately answered by the server. The server only sends an answer when some event is available or a defined timeout is reached. In that case the poll will be instantiated again right away by the client. In the mean time the socket stays open, the request does not consume any resources. In effect this allows push notifications.
How do I implement basic "Long Polling"?
Also obviously google will spit out tons of hits if you search for "php long poll".
Take a look at WebSocket - wiki.
Currently WebSocket supported by all popular browsers. You can check it here.
For PHP there is a good solution - Ratchet (http://socketo.me/)

Communicate from one page to another? JavaScript, PHP?

I'm building a prototype where on one page A I have a controller. Imagine a TV remote. On another page B, independent of form A -- it can be a different screen/computer -- with some elements X, Y, and Z that are going to be animated by the remote on page A.
My first idea would be:
Remote on page A saves an action wanted and sends JSON.
I create a listener on page B that reads the JSON to listen to what action to trigger.
I wonder if this the right direction.
It is just for a prototype so it doesn't have to be a production-perfect idea.
You can use web sockets for this.
Let's assume you're using 2 computers, both pointed at the website, as this technique could work in both scenarios.
If it's just a prototype, you could just simply have your page B poll the server every 5 seconds to look for updates that were submitted by page A.
However, in reality, for a production app with thousands of users, this could consume lots of bandwidth and put a heavy load on your server. To compensate for the load and bandwidth usage, you could increase the polling rate to 10 seconds, or 30 seconds, but in response to this change your users would experience delays while they wait for the browser to request an update from the server.
In a production app, many developers are turning to Comet as a solution. Comet is basically a term given by Alex Russell for a technique that involves using the request/response cycle to simulate server-push.
The general idea is that the browser makes a request to the server, and the server holds that connection open indefinitely. The connection remains open until another user posts an update to the server, in which case, the server then sends a response to the connected users.
The Dojo and Jetty team have demonstrations where they show that this technique can scale to 20,000 connections, when using continuations.
While I think you can carry out your experiment just fine with a database and/or some session variables, if your want to learn more about Comet on PHP, check out How to Implement Comet with PHP. Good luck!
UPDATE:
I also wanted to say that you definitely have the right idea for how to conceptually think about your message passing with JSON:
I create a listener on page B that reads the JSON to listen to what action to trigger.
I really like how you are thinking about passing a message that then tells the page what action to trigger. If you think about it, you could reuse your message passing concept to call other commands so that you avoid reinventing the wheel when a new command comes along that you need to call. Regardless of whether you poll, use Comet, or use WebSockets, it's a great idea to think about abstractions and generic, reusable data transports.
You could do this either with polling (having page B constantly poll for updates from the server) or use a server push technology like server sent events or websockets.
Yes, that would work. You could also just make it the same way you would make a vector line animation. Send the "commands" for movement to a server and record them (in a database, file, whatever) the client program can then request and redraw the movement smoothly any time and anywhere.
Using a cron job to execute Page B for every x unit time will make you check for any latest updated json (queried/returned output according your logic) from Page A. This way, you can use new updated json from page A and do your further task...

How does Gmail's periodic mail fetching work?

When I am using gmail, some new mails that I just received appear on the inbox, even if I did not refresh the page. I believe that would done in Ajax.
Is there any good demo that works very similar to it? Periodically checking and getting JSON data (I am not sure if it is JSON data..) to fetch new data??
Thanks!
The problem with periodic refresh is that while it is good for some things that aren't too time critical, like e-mail fetching, it is not instantaneous. Therefore you wouldn't want to use it for something like chat where waiting even five seconds for a response is too long. You could decrease the polling interval and make a request once a second or even half second, but then you'd quickly overload your browser and waste resources.
One solution for this is to use a technique called ajax long polling (known by others as 'comet' or 'reverse ajax'). With this technique, the browser makes a long duration ajax request, one that does not return until there is new data available. That request sits on the server (you need to be running special server side software to handle this in a scalable manner, but you could hack something together with php as a demonstration) until new data is available at which point it returns to the client with the new data. When the client receives the data it makes another long polling request to sit at the server until there is more data. This is the method that gmail uses, I believe.
That is the gist of long polling, you have to make a couple of modifications because most browsers will expire an ajax request if it does not return after a long time, so if the ajax request times out the client has to make another request (but the timeout is usually on the interval of a minute or longer). But this is the main idea.
The server side implementation of this is far more complicated than the client side (client side requires just a few lines of js).
While I'm not sure of the exact gmail implemention, the AjaxPatterns site has a good overview of what they dub a Periodic Refresh: --> http://ajaxpatterns.org/Periodic_Refresh. I've always just referred to the style as a heartbeat.
The gist of their solution is:
The browser periodically issues an XMLHttpRequest Call to gain new information, e.g. one call every five seconds. The solution makes use of the browser's Event Scheduling capabilities to provide a means of keeping the user informed of latest changes.
They include some links to real-world examples and some sample code.

What's the best way to coordinate javascript clients to a single backend game?

What's the best method to use to notify javascript client's of changes that occur in a game asynchronously (i.e. moves made by other clients). As an example, assume a turn based board game. Should I just have the client poll the PHP backend every second or so for new moves, or is there a better way to send an asynchronous notification to the other clients in the same game? What is your best idea for how to distribute the notification between the backend instances for each client?
I'm currently planning on putting each move in an SQL database and then having each client poll the database for new moves every second, but this seems kludgy and inefficient...
Polling every second or so is one option, but you may want to consider long polling instead, to reduce the latency.
Quoting Comet Daily: The Long-Polling Technique:
The long-polling Comet technique is a technique that optimizes traditional polling to reduce latency.
Traditional polling sends an XMLHttpRequest to the server in fixed intervals. For example, open a new XMLHttpRequest every 15 seconds, receive an immediate response, and close the connection.
Long-polling sends a request to the server, but a response is not returned to the client until one is available. As soon as the connection is closed, either due to a response being received by the client or if a request times out, a new connection is initiated. The result is a significant reduction in latency because the server usually has a connection established when it is ready to return information to return to the client.
Unfortunately there are only a few options for this. All will involve having some sort of client on the server sending down notifications if you want to use push technology. Or else polling is the way to go.
But just as a tangent here is a solution I played with years ago: http://www.spsolutionscorp.com/blog/2007/03/14/RealTimeUpdatesToWebPageUsingMacromediaFlash.aspx
The gist of it was this: Sql Server with service broker turned on. .Net service on server that is using SqlDependency to listen for changes to query result (http://support.microsoft.com/kb/555893). Once change occurred the .net service looped through all connections that had been made from a flash client that I wrote about in the above blog article. Then the flash app could call out to the javascript on the page.
It was a crazy idea and I never put into productions. But depending on your use it might be worth looking into and it was pretty easy to get going.
But again this was a totally crazy idea and again one I never put into production so use at your own risk. Just thought I would share.
Polling can easily stack up and consume a lot of resources (eg: bandwidth), no matter how lightweight your requests and responses are.
http://ajaxpatterns.org/Periodic_Refresh
You might want to try and use Comet/HTTP Streaming
http://ajaxpatterns.org/HTTP_Streaming

Categories