I presented my Brighton Ajax workshop yesterday. It all went rather smoothly. The workshop was in the same swanky building as the Clearleft office so I felt like I was playing on home turf. The homely feel was emphasised with the choice of snacks: Jessica was kind enough to bake up a whole batch of cookies for the workshop attendees. The cookies were a big hit.
During the workshop, I discussed the data formats available for Ajax responses. There’s XML and JSON, both of which can be parsed and then added to the document using DOM methods like
appendChild. Another option is to simply send back HTML from the server and dump it into the document using
innerHTML. If I ever find myself needing to update just one part of the page, this is the solution I use.
Suppose the part of the page I want to update is a
div with an ID of “container”. I can just add the HTML that has been sent in the
responseText property of
var container = document.getElementById("container"); container.innerHTML = xhr.responseText;
innerHTML can cause some problems, particularly in Internet Explorer. If you use
innerHTML to add or update
form elements, all sorts of screwiness can occur. Sometimes the data from the newly added elements won’t be included when the form is submitted to the server.
Toby Cole—a Brighton-based developer working at Semantico—was at the workshop. He proposed an ingenious solution.
First of all, use the DOM to create a block level element—such as a
createElement. Then update the
innerHTML property of this newly-created element. Finally, insert the updated element into the document using a DOM method like
var newdiv = document.createElement("div"); newdiv.innerHTML = xhr.responseText; var container = document.getElementById("container"); container.appendChild(newdiv);
Ta-da! The best of both worlds: the brevity and speed of
innerHTML but without the problems in IE.
See, this is one of the reasons why I like the intimacy of workshops. It’s a great environment to exchange ideas. I think I’ve learned something new from the attendees at every workshop I’ve presented but this one was particularly fruitful.
Posted by Jeremy on Saturday, March 3rd, 2007 at 7:53pm