Grab HTML fragment with AJAX

If you’re new to AJAX you may be wondering how you can pull in just a single element from another HTML page (as calling an HTML page with AJAX pulls the entire HTML content in as a String).

It has also been explained to me that the particular solution I’m going to discuss here is the same technique used by the jQuery library.

I’m not going to run through how to actually write an AJAX method as that is outside the scope of this post, so feel free to use your own home baked JavaScript code, or use any one of the numerous JavaScript libraries as they all include their own variation of a cross-browser AJAX call.

With most AJAX scripts you’ll also specify a callback function which will run once the requested data has been retrieved. In my case this looks something like this…

$.Remote.load({
	url: "Test.html",
	callback: function(response)
	{
		// Do something with the response object
	}
});

Once my AJAX function has successfully retrieved the data, it runs the callback function which then processes the data and grabs the element we’re interested in.

Within the callback function we first need to create a new element and then set the elements innerHTML to the response data (which is returned as a String).

We then grab all the elements we’re interested in (for this example I’m specifically looking for a DIV element that has an ID value of “content”) and loop through them until we find the relevant node…

// Load the contents of the HTML file 'Test.html'
$.Remote.load({
	url: "Test.html",
	callback: function(response)
	{
		// Now we have the HTML as a String 
		// lets parse it into a DOM node
		// so we can then locate an element 
		// within the HTML we want to pull in
 
		// Create an empty DIV which wont be used for anything
		// other than storing the HTML response
		var tempNode = document.createElement("div");
 
		// Set the DIV's innerHTML to the HTML String we've received
		tempNode.innerHTML = response.text;
 
		// Grab a reference to all DIV's in the 'Test.html' page
		var nodes = tempNode.getElementsByTagName("div");
 
		// Loop through each DIV found...
		for (var i=0, len=nodes.length; i<len; i++) {
			// ...looking for the DIV we want
			if (nodes[i].id === "content") {
				// Insert the found element into the page
				document.body.appendChild(nodes[i])
 
				// Clean-up
				var tempNode = null;
				var nodes = null;
 
				// Break the loop now we have found the element we want
				break;
			}
		}
	}
});

Simple as that!

Obviously you could clean this up a lot and write a function that takes in as an argument the element you’re looking for as well as a class name/id and then have it return the relevant content, but for this example I’m just using my own box standard AJAX code and searching through the response data from within my callback function.

Remember also that this is just example code and is far from perfect, but hopefully it has at least clarified the process of how to grab an HTML fragment from a separate HTML page using AJAX.

Tags: , , ,

One Response to “Grab HTML fragment with AJAX”

  1. TwoHawks says:

    Hey Mark, thank you for sharing that. I wish to point out to others finding this place under similar investigation as I that… well, I was tearing my hair out trying to figure out how to use responseXML method to work for pulling nodes from my html files, thinking that would be the efficient approach; however, after much searching testing and learning it appears that using responseText, which is what your method appears to be essentially based on, is the ‘free’-way to go, as handling XML nodes has some stringent requirements and is going to make you jump through hoops to get it to work with anything not plainly being served up as xml content-type.

    Although I am using completely differnt code than you are sharing here, the method is an important good one for visitors to consider.
    Cheers, TwoHawks

Leave a Reply