I need an example of comet refresh html when database is updated! - php

People,
I am developing a web page that need to be refresh everytime that the data base gets an update. I already have the checkDatabaseUpdate() done in my PHP code.
But now I reaaly need some help to develop a simple comet to wait for a response, and another to check for update.
Is there anybody with any simple example to help me?
Is comet the right solution for that?
Thanks,

What you want to say is that on the database are executed querys (INSERT, UPDATE, DELETE) in the backend and you want to refresh the front page of a user when that query`s are executed ?
Hmm .. use a jQuery (looping) to "Ajax check" for database update in the frontcontroller and then refresh.
function refreshPage () {
$.load('checkModifDb.php', function(response, status) {
if .... { do the trick here - check jquery load.api }
}
});
and then use setInterval( "refreshPage()", 10000 ); to run the function every 10 seconds and
refresh only if it founds that db was modified.
I can't think of anything right now but i guess with little modification you shoul do the trick. This is how twitter.com do it.

Is comet the right solution for that?
Because of the way that PHP works (having a web server daemon process incoming requests), combining it with long-polling techniques can make for an unhappy server. Each connected user is going to hold open a connection to the web server daemon. Depending on that daemon's configuration, you may find that comet is an effective denial of service attack against your own server.
You'd probably be better off with plain old short-lived ajax polling here.

Related

DB Connection on Ajax

I have a chat on my website, and it runs on AJAX calls. Knowing that the PHP script is being ran 2-3 times per second, is it a bad idea to connect to a database and pull / insert data? I am wondering if it will slow down my PHP significantly, or not change it much at all.
Sorry I can't comment yet, so i don't know if that's your answer..
So basically of course this will cause all lot of traffic on your database. Depending on Webserver this might not be that big of a deal. But if a Clients physic computer is just from 2000, his side will just lag out the tab because his browser is sending all the time requests to your database and is trying to get the answer.
But i think this is the easiest method to get live data, which you need for your chat. But in my opinion I would suggest you to run the AJAX-Request like every 2 Seconds. I don't know what's exactly your purpose. But for a normal chat (not real time data exchange) this will last.
By the way: I am also not sure how you are initializing your AJAX-Request. But i would suggest doing this with jQuery:
$(document).ready(function(){
call_php_ajax()
});
function call_php_ajax(){
$("#div_toinsert").load("ajax.php");
setTimeout(call_php_ajax, 3000) // 3 Seconds
And in your MySQL-Query-File (ajax.php) you perform your queries

need to refresh the page content

I am using codeigniter frame work and currently working on social networking kind of stuff. My problem is, i need to notify the user of their friends activity with out reloading the page when the user clicks on the feeds link.
I have tried the following script,
<script>
setInterval(function() {
$('#reload').fadeOut("slow").load('user_feeds').fadeIn("slow");
}, 10000);
</script>
It increases the load to my server. any other idea for accomplishing this.
Thanks in advance.
Then try to decrease the time interval
<script>
setInterval(function() {
$('#reload').fadeOut("slow").load('user_feeds').fadeIn("slow");
}, 1000);
</script>
Manoj what you are trying to achieve here is notifications and the data source residing on the server, so there is no way you can do that from the browser either by a pull or push from the server.
pull you can achieve by constant polling / frequent polling - usually by setting a timeout and getting the notifications.
push - ideally not really push you can achieve this by combining AJAX+Comet, this can also be achieved by long polling too where you maintain a constant connection with the server for any new updates and return data to server when there is an update.
let me know if this helps or you need more information
This is actually a very interesting problem, what you need is an implementation of COMET .There is an event routing bus using comet called COMETD. COMETD also has javascript implementation and has bindings for Jquery. http://cometd.org/documentation/2.x/cometd-javascript

Ajax auto updates and server load

I have a project that needs a sort of shopping cart that is always available at the top of the screen. Whenever someone hovers over the "cart" icon, a list of everything that's inside is shown.
However, if an user has two tabs of my site open, and in one of them something is added to the cart, the other one will be outdated and a refresh will be required.
My question is: if I use AJAX to constantly update the list of items (which will require sessions and database checks), will it be a big enough load on the server (or even on the browser) for it to be a problem, or is this common practice? If it is a problem, what other ways can I go so every tab an user opens is always updated?
If someone could show me the path so I can study more about it, even the name of what I should look up, I would be really grateful. Thanks.
there is no load on browser, just one more request in server ... maybe these requests are useless,
there is another way name server push
APE (Ajax Push Engine) :: Comet server :: Real time data streaming ->
http://www.ape-project.org/
nginx_http_push_module - Comet For The People -> http://pushmodule.slact.net/
node.js -> http://www.nodejs.org/
Socket.IO: the cross-browser WebSocket for realtime apps. ->
http://socket.io/
Comet with Nginx and jQuery | Coach J ->
http://blog.jamieisaacs.com/2010/08/27/comet-with-nginx-and-jquery/
if your request count is more than your server power use this way but if you have little request and not important you can use server pull frequently
Ajax is the solution here - it has a very light footprint.. as long as you don't use it indiscriminately, it is pretty much the same as reloading the page (much less if done correctly as its serving a smaller document). In fact, research has shown that ajax can cut the server bandwidth usage by over 60%.
You can read about the speed issue specifically here.
I learned Ajax over at Tizag, they have a brilliant Tutorial.
Hope this helped :)
you can make the ajax call on an interval to load the div with latest data. Something like this
(function getLatestCart(){
setTimeout(function(){
$("#latestCart").load("getCartDetails.php", getLatestCart);
}, 10000);
})();
this will call the method on every 10 sec(you can change the time interval) and load the latest cart to the div with id latestCart.
You can track locally this changes.
Use UserData (IE7 and down) or domStorage with updated data, and check every 10-20 seconds if the data was changed.

Whats an alternative way of updating a page with new records as they are inserted into a table automatically without using jquery/ajax

I've wrote a small chat system using jquery, php, and mysql; however, I'm looking for some kind of technology that will only update a if a new record is inserted into a row. I feel like using jquery ajax calls every second to retrieve new records is really overkill and strenuous on my server.
You are looking for a Comet solution: http://en.wikipedia.org/wiki/Comet_%28programming%29
The idea, as pdr noted, is to the javascript continuously open an async request with the server. The server holds it open, but does not send anything until it determines there is something to send. The request will timeout on the javascript side after 10-20 seconds, after which it should re-open the connection.
This uses a 'subscriber' based model, by which the server will send out the chat message or what have you, to all clients which are subscribed, all at once. This saves you many database requests, as the server is the one asking for the requests, not the individual clients.
What you want is long polling. Basically, you make an XHR, and the server and PHP holdes the request open until new data is ready to be sent back.
You need to configure Apache not to timeout in this circumstances, so do some substantial research. Basically, the PHP looks like so...
set_time_limit(0);
while (TRUE) {
$db->query('SELECT `message` FROM `messages` WHERE `new` = TRUE');
if ($db) {
echo json_encode($db->results());
exit;
}
sleep(1);
}
Then, you make an XHR for this page, and it will stay open until new data is ready. Then, on the complete callback, update your page's state and make a new XHR.
This is a lot more efficient than polling for updates continually using XHR.
Make sure you do a lot of research because I believe Apache is going to think things are wrong if a PHP script hasn't stopped after 30 seconds or so. :)
There are a couple routes I know of that you can take.
Long polling. This is where the browser opens a connection to the server and does nothing until the server responds. Once the server responds or times-out (sends an empty response to the browser), a new long-polling request is made.
When going this route, you should use a server that does not rely on using a new thread for each request.
Web sockets. Again, you'll want a server that can handle requests without spawning a new thread every request. With web sockets, a connection is kept open between the client and servier, and unlike Long polling, doesn't time out. However, this isn't well-supported yet.
I highly recommend checking out http://socket.io/
The point of Ajax is that it's asynchronous. Can you not just wait at the server until there's a worthwhile response to send?
With standard HTML/CSS/JS, that's pretty much the only way since the browser can make requests of the server, not vice versa. The AJAX call shouldn't have to be very big at all. A chat system, by definition, is going to require hitting the server a lot.

Synchronize Ajax response

I'm in a codeigniter environment and I want to do something like this.
There is a chatroom with a single O-wner and some C-lients.
This is what I'm trying to write
1) C joins the room.
2) when ready, all Cs clicks on a "ready" link that sends an ajax request
3) C waits for all the Cs to get ready, then signals all client and the previous ajax reponses are sent
4) when C receive the response (which should be in the same moments for all the clients) they start doing what-they-have-to-do :)
Is there an easy way to keep track of all the clients connected so that I can signal them all simultaneously?
For now I'm stuck at step 3. I have a code like this
$.ajax({
url: 'myurl.php',
success: function() { doStuff(); }
});
and in my hypotethic file myurl.php i have
while ($this -> MyModel -> waitingQueue) {
sleep(1) }
return "ok";
I guess this is not a good approach since I can't control whether all the clients receive the responses in the very same instane, when I change in my model the variable "waitingQueue".
Thanks all!
You can try to mimic synchronisation with a regular ajax check from all clients on a server. Check the jQuery.queue function, start a queue polling with SetInterval, and then push function containg the checks in that queue (and in theses functions flush the queue).
If you want to go one step further you should get a look at 'Comet' and persitent HTTP connections, trying to put PUSH behavior in HTTP, but it won't be simple :-) At least if you get the complete control of your network, server, people connecting to your app (like an intranet) it will be simplier.
Or you can check documentations on the now closed project google waves.
i recommend using setInterval() in javascript. so you can check continuously for server state.
i don't think you can synchronize your clients that simple. and they will not get the answer from the server at the same time.
if you synchronize the watches of all clients and arrange a collective point in time, when the client shell trigger an event, you might get a good chance.
...and don't forget clearInterval()

Categories