Page is a not externally linkable
Fotiman - 4:11 pm on May 8, 2012 (gmt 0)
I'd start by breaking this into smaller chunks.
/**
* Update the page title.
* @param {string} newValue The new title to set as the page title.
*/
function setPageTitle(newValue) {}
/**
* Given a message count, update the page title with the value.
* @param {string} msgCount The message count.
*/
function messageCountAsPageTitle(msgCount) {}
/**
* Send an AJAX request to get the message count from the server.
* @param {function} callback The function to call when the request completes.
* The callback should take 1 parameter, the string value of the message count.
*/
function getMessageCount(callback) {}
Then tackle each method one at a time.
/**
* Update the page title.
* @param {string} newValue The new title to set as the page title.
*/
function setPageTitle(newValue) {
document.title = newValue;
}
This method is so basic, we may end up eliminating it and just setting document.title directly from where we would have called this. However, it's helpful to see the required functionality broken down.
/**
* Given a message count, update the page title with the value.
* @param {string} msgCount The message count.
*/
function messageCountAsPageTitle(msgCount) {
// TODO: determine where 'another text in the page title' should be defined
setPageTitle('(' + msgCount + ') - another text in the page title');
}
That method is just doing some formatting of the string. Need to determine what "another text in the page title" should be and where that should be defined. For example, you may want to get the page title once when the page first loads, and use that text instead, allowing this script to go on any page in your site.
Now for the biggest chunk, the AJAX request.
/**
* Send an AJAX request to get the message count from the server.
* @param {function} callback The function to call when the request completes.
* The callback should take 1 parameter, the string value of the message count.
*/
function getMessageCount(callback) {
var url = 'file1.php?' + (new Date()).getTime(), // prevent caching
xhr = getXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.timeout = 20000; // Set the timeout to be less than the frequency we call this
xhr.open("GET", url, true);
xhr.send();
}
Let me preface by saying I haven't tested this. :) I think it should work though. It requires that you have a getXHR function defined (see [webmasterworld.com...] for an example).
Lastly, we need to kick it off:
setInterval(function() {getMessageCount(messageCountAsPageTitle);}, 30000);
This is setting the interval to every 30 seconds (note, I set the timeout on the xhr to 20 seconds).
Please be sure to post your success or questions here. :)