JavaScript
Article
By Simon Willison

Quick tip: XMLHttpRequest and innerHTML

By Simon Willison
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

--ADVERTISEMENT--

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?