I'm writing a website using PHP / MySQL. The website should allow users browsers to be automatically updated when a table is updated in a database (which is caused by someone inserting something though the PHP site). Basically, if the state of the table changes other users on the website should immediately see the changes.
I'm relatively new to PHP / AJAX and other web technologies. The only way I can think of doing this is to have the clients manually recheck the database every second or two via a timer (but this seems like a lot of wasted bandwidth). Is there some way to have the users automatically notified when the database changes?
Thank you!
You already had the solution in mind. You can use ajax to automatically check for changes.
It's not possible for the server to contact you when something has changed. It doesn't have to be bandwidth intensive when you lower the retrieval intervals. You can have Ajax check for a blank page with as little as possible text. That way the bandwidth usage wont be too bad.
Facebook does it this way too.
1) AJAX Polling.
As you say, use ajax to call the PHP on the server side to get
updates.
2) HTML5 Websockets.
Websockets are a new feature of HTML5 which allow the browser to keep a bi-directional TCP connection open to the server, where data can be transmitted both ways without polling. Currently this isn't as widely supported as ajax polling is.
3) Java Applet/ActiveX control.
Generally the most undesirable solution because of the user having to install third party software.
Related
I am writing a JavaScript for an in-browser IM client for the sake of practicing and learning JavaScript and AJAX.
I need to be able to check for a change in the file size of a text file that is being used as a temporary storage for 40-80 SQL entries that contain messages so that it can update the display.
At the moment I am using a setInterval function to periodically check for a change in file size using short PHP script, but this can cause issues, if the interval is to long, messages are delayed, if it is shorter, it means a lot of php scripts running very quickly, which takes up server resources.
What is the best way to do this if the main concern is to reduce server resource usage?
(I am running my server off of a rather low tech PC I've scraped together(2gb ram, 2.8ghz AMD seperon processor))
Preferably, I would want to do this using an AJAX event triggered by someone sending a message, I.E. When user B triggers the event that edits the file by pressing enter, that triggers a function on user A's side that updates the HTML file
Any ideas? I am open to any solution to this particular problem. I gave specific examples of what I want to happen in the specific languages in order to give a better idea of what it is I am attempting to do.
If there is a way to do this that isn't JavaScript/PHP, I'd also be open to exploring that as an option.
Doing this with PHP can be a bit cumbersome. You could try doing something like long polling where you keep the HTTP request open until the server has new data to send to the user. If messages are sent frequently, this might not be ideal. You might want to consider using event-driven web technologies like node.js with something like Socket.IO.
In any case, you'll likely want to maintain a connection with the server if you want to get the message in near real-time. There are ways to use WebSockets with PHP as well, but PHP isn't really the best for this because it's not designed to keep scripts running for long periods (also see What exactly entails setting up a PHP Websocket Server?).
Browsers & HTTP/ AJAX generally work by a "pull" model. The browser/ or AJAX sends the server a request, then the server answers a response.
There isn't generally much provision for the server to contact the browser, to "push" an event. This can however be simulated by a long-running request, to which the server writes data when the event/ or events occur.
For example, this could be a request that answers "empty" after a timeout of 10-30 seconds.. or the server returns & answers immediately, if there are event(s) in its queue.
With a Java server this is easy to do, and I've used this successfully for event notification in a major integration project a few years back.
However I'm not sure in PHP how much ability there is (probably very near zero) to maintain an overall server state, coordinate or communicate between threads/requests, or maintain event queues.
You could look into something like a Java webapp running on Tomcat. All you need is a basic web.xml and one Servlet class, and you can build just about anything from there.
I set myself a challenge today to write a jQuery chat in under half an hour. It eventually took me 40 minutes.
However, I want to improve it so the load on the server and browser isnt horrendous.
Currently the user types into a text box, presses enter, this data is sent to a .php file which updates a mySQL table and outputs all the rows on the table.
There is a set Interval on the div every two seconds to update if anyone said anything without the user pressing enter.
I just wanted to know thoughts on how to do perform this in a better way, or the most efficient way. I want to understand the best technology to use and why.
Thanks for all your input, I love stack overflow, its been invaluable to me.
Using ajax polling for a chat application with the "php back"/"javascript front" technology stack will inevitably result in a heavy server load. Http is just not designed for that kind of communication, and if you're using apache (as I assume) there is a really heavy overhead for each request.
As some of the commments indicated, you could investigate using a full stack javascript framework (i.e. Node.js on the backend).
When I had the task of accelerating an existing chat application with php backend and Javascript frontend (using periodic ajax poll), I ended up using a 3rd party server side product to handle lightweight XMPP requests. This server side product was OpenFire, but you could use eJabberd for even better performance - OpenFire is easier to set up and maintain though. The results were more than satisfactory, server load dropped significantly, and messages were delivered instantly for ~1000 online users chatting wildly away (on a less-than-average performance dedicated linux box).
It's hard to explain all the tiny details within a SO answer's scope, but luckily Ben Werdmuller # IBM went out of his way to write an awesome tutorial on this topic.
I am creating a web app that requires a live notification system. How would I set up my server to pull data from a mySQL database and then push it to the browser. I have absolutely NO idea how to do this. If anybody can help, it would be much appreciated! Thank you so much!
EDIT: I should probably be more specific, I am pulling data as in XYZ recently created an account, XZY recently ... Thanks so much!
You cannot push data to a browser, but what you can do is set up your webpage to poll your server every few seconds for updates. An example setup would be:
From within your website, have a javascript function that runs on a timer every few seconds (or whatever interval works best for your situation).
Start that timer on page load.
That javascript function invokes an AJAX call to a web service on your web server (more on that in a second).
On the server side you'll need some sort of system that tracks these events and stores them somewhere such as in a database table with a timestamp. So for example when XYZ creates an account, that would be logged in this "event" table in the db.
The web service called by the AJAX call will then run a query on that table and retrieve all entries since the last time it was called. Then just update the webpage with those results.
It's obviously not 100% "live" as there will be a small delay depending on what time interval you set in the JS timer but it's pretty close.
You can create a push notification service for your website utilizing websockets and graceful degradation to a long polling fallback for browsers that don't support websockets. This does require a healthy amount of technical/programming knowledge.
Some good resources for this are:
http://socket.io (which uses a node.js backend for the web sockets and handles degradation)
http://pusherapp.com (a commercial solution if you don't want to roll and maintain your own service)
For a list of browsers that support websockets, you can search for "caniuse" -- which provides great details to features supported by browser versions
Note: For multi-million user applications like Facebook, I would assume they've weighed the advantages of running websockets for 50+ million simultaneous users and concluded that keeping data consistent across all the nodes connected to the millions of sockets would be too much. I can imagine it would be a logic nightmare to do that on a socket system instead of a basic action sql-like infrastructure. I can't speak on their behalf though, this is simply my assumption. However, you'd be surprised how many sites have been using push and polling systems lately :)
I want to create a live, checkers-like app, which will work like this: There will be multiple icons/avatars displayed on this checkerboard like surface. I want to have a command prompt beneath this board, or some other sort of interface, that will allow them to control a certain avatar, and get it to preform actions. Multiple users will be using it at one time, and I will all be able to view the other user's changes/actions to the checkerboard.
What I'm wondering is: what's the best way to do this? I've got my HTML, CSS, and JS approach down, but not my data storage method. I know that, using PHP, I've got the choices to use either: file-based storage, MYSQL, or some other method. I need to know which is better, because I don't want to have server-lag, poor-response time, or some other issue, especially in this case since actions will be preformed every other second 2 or so, by these multiple users.
I've done similar stuff before, but I'm wanting to hear how others would handle it (advice, etc.) from more experienced programmers.
Sounds like a great project for node.js!
To clarify, node.js is a server-side implementation of javascript. What you'll want is a comet based application (a web-based client application that receives server side pushes instead of the client constantly polling the server), which is exactly what node.js is good at.
Traditional ajax calls for your clients to poll the server for data. This creates enormous overhead for both the client and the server. Allowing the server to push requests directly to the client without the client repeatedly asking solves the overhead issue and creates a more responsive interface. This is accomplished by holding asynchronous client connections on the server and only returning when the server has something to respond with. Once the server responds with data, another connection is immediately created and held by the server again until data is ready to be sent.
You may be able to accomplish the same thing with PHP, but I'm not that familiar with PHP and Comet type applications.
Number of users and hosting costs will play into your file vs DB options. If you're planning on more than a couple of users, I'd stick to the database. There are some NoSQL options available out there, but in my experience MySQL is much faster and more reliable than those options.
Good luck with your project!
http://en.wikipedia.org/wiki/Comet_%28programming%29
http://www.nodejs.org/
http://zenmachine.wordpress.com/2010/01/31/node-js-and-comet/
http://socket.io/ - abstracts away the communication layer with your clients based on their capability (LongPolling, WebSockets, etc.)
MySQL and XCache !!!!
Make sure you use predefined statements so MySQL does not need to compile the SQL again. Also memtables could be used to use memory storage
Of course make use of indexes appropriately.
If the 'gamestate' is not that important you can even store everything in XCache.
Remember that XCache does not store data persistently (after Apache restart)
I need to implement real-time page data update with php and jquery.
(I found www.ape-project.org/ but it seems site is down)
Is any other solutions?
Very TNX!
You might want to check out Comet:
Comet is a web application model in
which a long-held HTTP request allows
a web server to push data to a
browser, without the browser
explicitly requesting it.[1][2] Comet
is an umbrella term, encompassing
multiple techniques for achieving this
interaction. All these methods rely on
features included by default in
browsers, such as JavaScript, rather
than on non-default plugins. The Comet
approach differs from the original
model of the web, in which a browser
requests a complete web page at a
time.
http://en.wikipedia.org/wiki/Comet_%28programming%29
If you want to do streaming (sending multiple messages over a single long lived, low latency connection), you probably need a comet server. Check out http://cometdaily.com/maturity.html for details on a variety of server implementations (I am the maintainer of one of them - Meteor).
If you are happy to reconnect after each message is received, you can do without complicated servers and transports and just use long polling - where you make an ajax request and the server simply sleeps until it has something to send back. But you will end up with LOTS of connections hanging off your web server, so if you're using a conventional web server like Apache, make sure it's configured to handle that. By default Apache doesn't like having more than a few hundred concurrent connections.
There is lots of solutions to do this...
Depending on what is your data, how your data are organized and stored (mysql ?).
Your question is too open to have a real answer.