Here at Road to the Middle Class we are nothing if not modern. That means that the site ought to be LAMP compliant, using Linux, Apache, MySql, and PHP, and so it does. But now, according to The Economist and Eric Schmidt, CEO of Google, it appears that a truly modern site should use AJAX as well. AJAX (Asynchronous JavaScript and Xml) is the technology that Google uses on GMail.
Well, how hard could it be?
The standard demonstration of AJAX on W3Schools.com shows how to use an AJAX setup to update text hints on the fly. You press a key to enter a character in a text box and every time you release the key your page requests a new text hint from the server with an HttpRequest.
When the response comes back from the server you update the text hint element like this:
document.getElementById("txtHint").innerHTML =xmlHttp.responseText And everyone is happy.
But there’s a problem. The best use of AJAX here at Road to the Middle Class is to fold/unfold blog entries. We conserve real estate by showing only the first 50 words of a blog and allow you to click a link to get the whole article. But that means that the content coming back from the server is going to include HTML markup. What happens if the responseText isn’t just simple text but includes embedded HTML?
Good question. It turns out, using the W3Schools example, that embedded HTML works on Firefox but not on our friends at Internet Explorer: IE6 and IE7. The IE boys take one look at the embedded HTML and decide that it’s not a job for innerHTML. They return an "unknown runtime error".
Here’s how you update your page with AJAX when the responseText is complex and includes embedded HTML as it is here at Road to the Middle Class. I call it the Double Span Solution.
First of all, you surround your text with two <span> elements, like this:
<p><span id=blog101><span id=blog101s>
<p>Text including a <a href="">link</a> and stuff.</p>
</span></span>
</p> The idea is that when you want to replace the text in the middle of the two <span> elements you replace the entire inner <span> element. You delete the old <span> and add a new <span> with the responseText and all of its HTML markup.
First of all you set up the new <span> element, preserving the element id from the old <span> element and adding in the responseText from the server.
var elem = document.getElementById("blog101s")
var newSpan = document.createElement(’span’)
newSpan.id = elem.id
newSpan.innerHTML = xmlHttp.responseText
Now remove the "blog101s" element and anything else floating around.
for (var i = 0; i < document.getElementById("blog101").childNodes.length; i++) {
var n = document.getElementById("blog101").childNodes[i]
n.parentNode.removeChild(n)
} OK. Now append the new <span> element right under "blog101".
document.getElementById(gBlogid).appendChild(newSpan) And that should do it.