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. Quick and Easy Graphing with the Google Chart API The Google Chart API makes creating simple charts and graphs...
  2. Security Tip: Update Your Flash Player Adobe applications come under more fire with alerts of serious...
  3. Better Selections In Photoshop With Quick Masks The Quick Mask in Photoshop offers a really easy way...
  4. Photoshop Tip: Locking Transparent Pixels Jennifer demonstrates how the Lock Transparent Pixels button can help...
  5. Mozilla Jetpack: Firefox Extensions with Added Thrust Craig looks at Mozilla's new Jetpack project, a potential glimpse...

This post has 44 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...