Send Response to all active session when database data changes - php

I want to send a response to all users which are currently active (Logged or viewing content) when the database data changes.
Example
Some user is viewing "data" table.
Currently I'm executing AJAX calls every 5 seconds and if there is change in data database response the client will be notified.
However I no longer want to do it this way.

The alternative for ajax polling (as you did) is using comet/server-side push.
In other words, you would use something like WebSockets, Ajax long-polling, Server-Sent Events, etc., to send messages to the client instead of the client polling.
For the sake of this example, I'm going to use WebSockets. What I describe below applies to the other methods as well, though.
If you already have an existing PHP application, the simplest way to do this would probably be to write a separate "daemon" script which handles the sockets. Whenever your application changes some data in the DB, you would send a message to the daemon script, which would then notify the connected clients of the change.
You could use something like ZeroMQ for messaging between the main app and the socket daemon.

You can use polling or websockets, maybe Pusher.com is a solution for you.

Related

Can more browsers receive server events from the same PHP script's instance?

I want to implement a PHP chat with multiple Rooms, however I don't want each browser polling the server, instead I prefer the server send the updates to all users in each room. Ideally I would have just a PHP instance running for each room (plus of course the AJAX requests sent by users for updating the DB, I know server side events are not widely supported):
users POST messages using a POST AJAX request
when the PHP script of a Room read the DB and find a new message, it will sent the update to ALL the users connected to that room, this way it will be more responsive and would put less pressure on DB communication
So basically If there are N users and K rooms I want to reduce the overhead from
N database/php poll requests every while
to
K database/php poll requests every while
You might better use web sockets for this purpose. If you want to use php, there are few libraries for that:
1) Ratchet
2) ReactPHP
3) d-Node
and others. I used Ratchet and React. They work fine, as for me
Yes, but it will require writing your own web server: i.e. a socket server in PHP to receive http requests from clients. You then just keep one array of sockets per chat room, and when you get a message you want to broadcast to all listeners, you create and send an SSE message to each client, something like:
data: {room:12,msg:"Hello World"}\n\n
(I think by registering the socket into multiple arrays that you can even use a single SSE connection to listen to messages from multiple chat rooms. So, you could even have a single PHP process running all chat rooms.)
However, if using, say, Apache+PHP, then what you want is not possible. Each SSE connection will get a dedicated PHP process. (If this is your only choice and polling the DB is really expensive, you could have a single process poll the DB, then push messages to an in-memory localhost DB, and have each PHP process poll that in-memory DB.)

Send info from One browser to another in Laravel 5.2.37

I have a page where user can Add/Update records. Code is written in Laravel 5.2
Let's say I opened the that add/update page in chrome and same url in FireFox. So, if user create a new record in Chrome browser, info should be received immediately to Firefox. So, that I don't need to send ajax based reqeust to server to show complete list.
My question is, where should I start for this? Is there any blog that I can go through step by step ?
You definitely need to use WebSockets to achieve it. There a couple of good links in the tiagoRL's answer. But also, since you said you are using Laravel 5.2 I strongly recommend you to broadcast events. If you are a Laracasts user, take a look to the related videos.
Basically this is the main link:
https://laravel.com/docs/5.2/events#broadcasting-events
Also to simplify the server-side stuff, I'd go for Pusher
To have this kind of realtime messaging between two or more clients you'll need to use sockets. One option is to use AJAX pooling, but if you want to be real time, then use sockets.
With sockets you can create connection tunnels between many clients, however you will still need a server implementation. Due the this nature of persistent connections, you'll need a server architecture that can support many connections open at the same time, that's why NodeJS non-blocking IO comes in hand, using less resources than PHP would, for example.
More about this can be found here: http://www.html5rocks.com/en/tutorials/websockets/basics/
On the client side, there are websockets, which is a feature implemented in HTML5 compliant browsers.
References:
Here is a tutorial: https://blog.kaazing.com/2012/08/08/a-step-by-step-tutorial-of-building-a-simple-peer-to-peer-websocket-app-part-1/
One server implementation is available for NodeJS called Socket.IO http://socket.io/
The video here shows exactly what can be done with it: http://tutorial.kaazing.com/
Another good reference: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
This is a very normal thing to do and is achieved via AJAX background polling. You can do
Assumption
If user must be authenticated to see the page, in both browsers the same user is logged in.
Demand is low, so server load will be minimal.
If this is not true, look into web sockets.
Structure
Route for page (that you already have)
Route to return rows
all rows
rows starting from certain point
So the page loads and retrieves all rows, either server side or client side. Set the last row ID as a JavaScript variable. Then set an AJAX call to a timer. The AJAX call sends the last row already on the page, if there are new rows they are returned and the last row variable is updated. Alternatively you can use timestamps to track which rows are new.
There is no way of sharing session or cookies across different browsers.
Your problem is also unrelated to the programming language / framework in which your project is written.
The way I recommend you is to make periodical ajax calls to fetch newly added rows only in order to prepend or append them to the current list.
This way, you save lots of resources and time not refreshing the whole list.
Although I have never used it, if you prefer a persistent connection than socket I/O is the way you should follow.
You can check the following page for more info on ajax or socket I/O comparison.
http://www.cubrid.org/blog/cubrid-appstools/nodejs-speed-dilemma-ajax-or-socket-io/
I hope it helps you.
You can start with this:
Step by Step Guide to Installing Socket.io and Broadcasting Events with Laravel 5.1 using Laravel Homestead
This example shows you how use real time events.
The idea in your case is to send an event when a new record is saved or updated, and when the others receives this event, refresh the list of records.

Dynamic data updating

I'm making an app which accesses a database and updates the data every view seconds over a PHP script, the problem is that it currently always updates all data, I would like to know how to program something that dynamically updates data and decides what data to update and what not, so it basically keeps track of change somehow. So how would I best go along doing something like this ?
I think that there should be some where that this question has already be asked but I couldn't find it so maybe someone can show me a website where to look.
In general, you will need to user either XHR requests, web sockets, or HTTP/2 to solve this problem. Since HTTP/2 is not universally supported on the browser side, it may not work for you. Here is the outline of the solution:
Every few seconds, javascript you provide in the browser will need to poll the server for updates using an XHR request. You can use the returned data to update the screen with Javascript. If you only want to do some simple updates, like updating some numbers, you might use raw Javascript or jQuery. If your polling will result in complex screen updates or you want to move a lot of functionality into the client, you probably want to redo your client using one of the JavaScript frameworks like React or Angular.
Use web sockets (or HTTP/2) to create a persistent connection to the server, and have the server send updates to the clients as the data changes. This probably will require some code in the application to broadcast or multicast the updates. The client code would be similar to case 1, except that the client would not poll for updates.
The polling solution is easier to implement, and would be a good choice as long as you don't have too many clients sending polls at too high a rate - you can overwhelm the servers this way.

how to make a popup chat application without using ajax

I have made a dating website where I have use one to one chatting application like facebook. When one user send any message to another user it showing into their popup chat box, but I have done this using ajax. Which I have run in every interval using javascript setInterval function. But I think the process is not optimize one. I don't want to make unnecessary request to the server each time, rather it only trigger when there is some new message for that user. Is there any other way to do it or any other protocol which using by big site like facebook, gmail?
You could do this using WebSockets, but that requires both a server implementation and a web browser that supports it.
Another technique is to use Long Polling, but again, this requires work on both the client and the server. The advantage is that this is a cross browser compatible technique.
I agree with Josh that WebSockets would be worth looking into, however if you don't have access to the server you could use something like Firebase for the back end.
https://www.firebase.com/index.html
Read into Long Polling. It's what facebook uses. Basically your client makes one Ajax call and nothing gets returned until there is data to push to it. I'm pretty sure it requires some custom server configuration so if you're developing on shared hosting it isn't going to cut it. Long Polling would be the right, albeit, more complicated way of doing this if efficiency is what you want.
Server-Sent Events seems to be another option.
A chat example: http://motyar.blogspot.com.es/2012/01/simple-chat-application-with-html5.html
Documentation: https://developer.mozilla.org/en-US/docs/Server-sent_events

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...

Categories