I am looking to have an auto refresh a la Facebook homepage. I have already implemented the Ajax code but I am wondering what is the best way to go about the refresh.
I can do a setInterval and have it refresh every X minutes, but this seems unnecessary when the site is open in a tab, but not in use.
I can bind it to an event like mouseover (which i tested) but then it refreshes every time the mouse moves over the div, and for the most part is unnecessary. (as well as creating a heavy load on the server.)
I suppose ideal situation would be when there is a mouseover, it checks how long ago it was last updated, and if its been more than X minutes, do a refresh. Which I suppose is a combination of both the above methods.
Is there a way I don't know about? What about some kind of method that is implemented on the page where my div content comes from (my own page located on the same server), that waits for new material then "pushes" it to my div, instead of of my div going and "pulling" the info from the page?
Facebook does it using a keep-alive connection.
This means, an ajax request is sent to the server with a Keep-Alive header. It will stay alive until new content is available, the server then returns the response and the connection closes. As soon as this happens, a new keep-alive connection will be established etc.
On the PHP side, you can use sleep() in combination with an endless loop to check for new conent.
However, I don't know how much this affects your server's cpu usage...
Related
I'm at the conceptualizing stage of developing something but not quite sure of a certain feature.
I have a DIV in a form, lets call it id='divComments'. This div contains all of the comments on a particular title. It retrieves all of the data from the database which is easy to do.
Now when the page is refreshed, this div is populated with all of the comments. If another user adds a comment, all of the other users will see this comment when they log on (after that point in time) or if they refresh the page.
What if I want this div feeding from the database and refreshes automatically when something is inserted into the relation/table in the Database? so I have my page opened (im not refreshing it, just staring at it) showing lets say x and someone else adds a tuple in the particular database table lets call that y, and my div now shows x and y. In other words its updating real time from the database without refreshing.
Anyone has any idea how to go about doing something like this?
HTTP is stateless. Once an asset has finished downloading through a HTTP connection, the connection is destroyed and the server no longer has any knowledge of what the client is doing next.
There are ways of fudging stateful behaviour, using cookies and sessions and the like, but these still require a new connection to the server to fetch fresh data.
There are technologies in development that can allow a web server to "push" new data to the client the instant it becomes available (websockets, server-sent events, etc), but these are still at the draft stage for the most part and browser support is spotty at best.
The only real choice you have is polling the server with a refresh meta tag (EXTREMELY inefficient!), polling the server with AJAX (Better, in that you can design it to only fetch the data that's changed, but still not ideal), or using a long-lasting AJAX connection that remains idle until new data becomes available, at which point the data is downloaded, the connection is closed, and a new connection is opened to sit idle for more data (will allow immediate response, but difficult to set up properly).
There might be some cases that your request takes long time because
of some problems with your client internet connection or your server
connection. So since the client doesn't want to wait he clicks on the Ajax
link again which sends the request to the server again which messes up
the following:
Rendering of our website in the browser because we are giving extra
load to the browser.
What if the second request processed correctly and you showed user
the page and then comes along the error message from your first
request(saying request timed out) which loads above on the correct
content and mess up with the user reading the correct content.
I want to stop the 1st Ajax response if the Ajax function is called twice. How do I do this?
so i want to stop the 1st Ajax response if the Ajax function is called
twice
What you actually want is to prevent a second request when a first request is in progress.
For example, You may have to change the Save button to Saving..., disable it (and add a little progress wheel) to give live feedback to the user. (Facebook does this)
The key is love feedback to the user. If the user is clueless on what is going on, they are going to think nothing is happening.
You might want to check why the operation is taking long
If this is a complex/time consuming operation, like, say a report generation or a file upload, a progress bar should do
If this is because of the client's internet connection, say it up front, like Gmail: Your have a slow Internet connection and this site may be slow. Better still, provide a fallback option, with less/no Ajax.
You say cause we are giving extra load to the browser: this is kind of fishy. You will not be giving extra load to the browser unless you are giving it tons of HTML to render. Use Ajax only for small updates on the browser. You may want to reload the page if you expect a large change.
How bout seeing as your using some form of JavaScript to begin with you have that link either hidden or disabled in a manor of speaking til the pages request has been followed through with. You could for example have the requested ajax wait for a second variable that would enable that link so a user could click it. But until that variable is received from the original AJAX request its disabled to the click, then if it is clicked it disables again and waits for the same variable to come back again.
Think of how some developers disable a submit button on a form so a user can't double submit there form.. same concept of notion here.
I am curious as to how Facebook pushes data to the browser as in the news feed. New data shows up at the top of the feed without reloading the page or clicking a button
Does Facebook achieve this by polling their server through AJAX at a set interval or do they somehow push new data from the server to the client unprovoked?
If so what language or API do they use to do this?
It's actually called 'long polling', or 'comet'. There are different ways to perform server push but the most common way is to keep connection open while it receives data (it has drawbacks as browser have limit of number of open connections to a host). Facebook had open-sourced the Tornado web servers, which can handle a lot of open connections (which can be a problem is you have a lot of users, but you are using apache for example). In the moment you receive AJAX response, you simply perform a new request, waiting for next response.
Essentially the code does an AJAX call to their servers, and either waits for a response which triggers another request, polls on a timer, or they open a websocket to receive data as soon as it's pushed. This of course is for "new" data showing up at the top of the feed. When the page is reached at the bottom, they just do another AJAX call to get the next n items.
They push it with AJAX, and they use (at least they USED to use), infinite scrolling.
So you'd load your page, and they'd make an initial call to the server to load some messages based on who is logged in, say with a framework like JQuery:
http://api.jquery.com/jQuery.ajax/
And then as you scroll down, they make note of when you're close to the bottom of the page and they need to load more so you're not left without data, and then they make another call automatically. This is called infinite scrolling, and keeps track of where you are in the DOM:
Just one example: http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery
In my php application, I'm using $_SESSION to track whether a user is logged in. If a user leaves any page on my site at http://mysite.com and goes to http://someotherwebsite.com, I want to automatically log them out, such that if they return to any page on http://mysite.com, they need to login again.
Is there an easy way to do this?
You cannot explicitly tell when an user leaves your site, your best bet would to be to implement a timeout on your sessions.
As most of the answers have said, you could check with the JavaScript event onbeforeunload but the user can by-pass this by disabling JavaScript or, as BalusC had pointed out, using a web browser that does not support it, such as Opera.
Therefore, I strongly believe implementing a timeout on your sessions is the best way to force a logout.
You could perform an AJAX call in the onbeforeunload event to some server side script that will kill the session.
Except for putting a timeout on your sessions - not really. The only way that comes to mind is the onbeforeunload JavaScript event that fires when the user leaves the current page, but that event doesn't know where the user is going. You could however, if you really want to do this, maybe build something based on the following hacky workaround (untested):
set an onbeforeunload event that sends an AJAX call to your server. (How to do this successfully - so the call gets through before the page gets closed - is an issue of its own, a search for "onbeforeunload ajax" on SO should yield some results.
The Ajax call would start a countdown saying that this user's session is about to die in, say, fifteen seconds.
If the user is leaving your site, the countdown applies.
If the user is going to a different page on your site, you clear any "die" countdowns when serving the next page.
This is likely to be shaky because it could happen that an Ajax request starting a countdown arrives at the server after the next page has already eliminated that countdown. But if you really need to do this, this may be a direction. Works for users with JS enabled only, of course.
A second idea how to implement this would be to put an extremely low timeout on sessions (e.g. 90 seconds), and to put an iframe on every page you serve. That iframe would then make a call to the page every 60 seconds.
This would work without JavaScript, but could create annoying clicking noises in older versions of Internet Explorer (I don't know whether that stopped in 6 or 7?)
You can't (but your sessions will time out automatically after a while ; so you could set the timeout to a short time).
From what I know about PHP (which isn't much) would your application ever know they left the site? If you go to someotherwebsite.com, your code isn't called again until they return.
Unfortunately Not Really,
This is one of the big problems with web applications. Your applications has no way of knowing that the browser has moved on to a different website.
As ChristohpeD mentions you can set the session timeout.
Just remember that your site will only refresh the time when the server recieves a post or some kind of javascript ping.
Hope That Helps
I have an ajax application where the client might lookup bunch of data frequently(say by key stroke), the data gets updated on the server side once or twice a day at fixed times by a demon process. To avoid visiting the server frequently, I store the data in a xml file, so the client downloads it once when the page first loads, then look the data up from local data file via javascript.
But the user might load the page shortly before the changes, then start using it without ever refreshing the page, so the data file never gets updated, hence keep telling user the new data is not available.
How do I solve this issue?
You should set the appropriate HTTP cache headers for that generated XML file so any client request past that time will get the new version and cache it locally, like any other static content.
If the data load is not very large... Include the data in the main document as an XML island. Either form it in document generation (aspx, php, whatever) or fill in (via ajax calls) a reserved document node upon loading. This way, your user always has the latest data, you do not have to worry about caching, and life is much simpler.
If it is large, fill in that node as needed via ajax calls.
One obvious option is to add some AJAX that polls the server every x minutes. If the data needs refreshing just show a non-blocking message somewhere obvious on the page notifying the user that fresh data is available and provide a link to refresh the page. As an extra you might want to provide a button for the user to click if they want to check for fresh data (rather than waiting for x minutes to elapse) themselves.
If you use a HEAD request you can just check the last-modified header.
You said that the update time is FIXED? So when the user visit your page SHORTLY before the update time to come, you can set a javascript variable to you page that indicate how many minutes, for example, until the next update, and run a client-side timer such as:
timer = {
run: function() {
if( now + minuteToUpdate > updateTime - startVisitTime ) {
// make ajax request here to update XML file
}
},
interval: //you can determine this since this will run in client-side
}
Do not you POLLING in this stiuation because it's waste and stressed to call server every time.
You can set some SESSION variable to help this run better and more exactly
Justin
What runtime said...
Or, since update times are fixed and infrequent, then when you serve your XML, also include a cache expiration time as an element or custom header. This way, if your user visits the site 1 minute before the XML update, you can code your client to expire its cache and update itself on the next request made after that 1 minute mark.