Blog Post RSS ?

Blogs » JavaScript & CSS » Quick tip: XMLHttpRequest and innerHTML
 

Quick tip: XMLHttpRequest and innerHTML

by Simon Willison

XMLHttpRequest is one of modern DHTML’s best kept secrets. If you haven’t encountered it before, it’s a method of making an HTTP call back to the hosting web server without refreshing the whole page – a kind of remote scripting on steroids. Originally a Microsoft extension, it’s been adapted by both the Mozilla browser family and (as of version 1.2) Safari. The Sarissa library discussed previously offers an abstraction layer for the different browsers, or for a more lightweight approach this code from jibbering.com (which makes use of IE’s JScript conditional compilation) works perfectly.

Getting the most out of XMLHttpRequest generally involves using server-side generated XML, which can be retrieved by your JavaScript application, parsed and used in more complex logic. However, for a quick fix the following code will load an HTML fragment from a URL and insert it directly in to a page:


function loadFragmentInToElement(fragment_url, element_id) {
    var element = document.getElementById(element_id);
    element.innerHTML = '<p><em>Loading ...</em></p>';
    xmlhttp.open("GET", fragment_url);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            element.innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.send(null);
}

Call the above function with the URL of the HTML fragment to be inserted and the ID of the element in which it should appear. It relies on the jibbering.com code to set up the xmlhttp variable.

It’s definitely quick and dirty, but it’s also a great quick demonstration of the power of the XMLHttpRequest extension.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. A Quick-And-Dirty Way To Update Your Firefox Extensions For Firefox extension users, not extension developers, this post details...
  2. What’s the difference between function.call and function.apply? Function.call and function.apply are a couple of very useful methods,...
  3. Photoshop Tip: Locking Transparent Pixels Jennifer demonstrates how the Lock Transparent Pixels button can help...
  4. Mozilla Jetpack: Firefox Extensions with Added Thrust Craig looks at Mozilla's new Jetpack project, a potential glimpse...
  5. Firefinder Adds Search to Firebug Everyone loves "the Firebug," and one of the nicest things...

This post has 44 responses so far