Append with ajax

Hi there,

So I’m trying to append some data from a remote file using jQuery.

Originally I was just using the load function like so:


$('#target').load('object.html #content);

which is fine, but I need to attach event handlers to the loaded html, and that’s become problematic.

Instead I want to now append the loaded content to the DOM, rather than replace the contents of the target div with the content div.

I thought about putting it into a variable, but I’m not sure of the syntax for that, or even if its possible.

I tried:


$.get('object.html', function(data){
	$('#target').append(data);
});

But that appends the entire page, and all I need is one little div!

Any ideas?

Many thanks,
Mike

The .load method can take three parameters, 1) url, 2) data (to accompany url) and 3) complete function (to be executed when completed).

If you want to have event listeners then the first parameter is the place to do it.

Hi Phillip, thanks for your reply. Reading my post back, I think it was a little unclear.

I want to append a section of a HTML page to a target div in another HTML page using jquery. Once that’s happened, I need to attach a click event handler to a certain number of anchors on the loaded HTML.

I have achieved the 2nd half using a callback function on the .load method. As for the actual HTML, I have to load it into an existing div, rather than append it to an existing div. This just creates more markup which seems needless. I was wondering if I could just append the fetched div to the DOM somewhere.

Regards,
Mike

You could try using the .delegate() method. If you apply it to the div that its going to receive the content it should work well.
E.g.


$("#somediv").delegate("a.somelink", "click", function(e) { /* code here*/ });

Thanks AussieJohn, delegate will certainly be useful, and will most definately speed up my script. But it’s not really the event that I’m worried about. What I’d like to know is: is there a way of appending data from an ajax call, rather than loading it.

In the case of the load method, let’s say i do this:


$('#target').load('example.html #fetch');

The result will be:


<div id="target">
  <div id="fetch">
    ... some content ...
  </div>
</div>

Where what I want is:


<div id="target">
  ... some content already in the DOM...
  <div id="fetch">
    ... fetched content from remote html ...
  </div>
</div>

Which is basically appending the fetched div, rather than loading it, which will replace the contents of the target div with the new div.

I thought perhaps I could do this by instead of loading the fetched div into the DOM, I could store it into a variable, and then append that. Something like:


var html = $.load('example.html #fetch');
$('#target').append(html);

Is that possible?

Many thanks,
Mike

This is what .load() does… it will replace the contents of a div with fetched data…

This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is “success” or “notmodified”), .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:

$('#result').load('ajax/test.html');

If you mean to get the HTML and append it rather than replace the contents of your #target, you’ll probably need to append a div with a unique id first.

E.g.:

$(document).ready(function(){

	$("#btn").click(function(){

		var uid = uniqueId("loaded_data_");
		$("#target").append("<div id='"+uid+"'/>");
		$("#"+uid).load("example.html #fetch");

	});
	

});

//borrowed from Underscore JS (https://github.com/documentcloud/underscore/)
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.

var idCounter = 0;
uniqueId = function(prefix) {
	var id = idCounter++;
	return prefix ? prefix + id : id;
};	

One of the downsides is that you will end up with <div id=“fetch”> … </div> in each of these unique divs, which means that you’ll not have a unique reference to #fetch (you’re not allowed to have multiple items with the same ID in a page).

Though you could write a callback function that gets called after .load() is called that then renames #fetch to something unique.

mickyginger Not sure because I’m not an expert but I don’t think I’m not in the same space you are in. I need html to be loaded to a div in my page and I don’t use Ajax I use object and js and the only problem I found is the loaded html in the object has to have the script written in script tags at the bottom of that html page and can’t use external js by relative link but the external.js was easy to copy and paste into the script tags at the bottom of the fetched html which works fine. No php, no jquery
EG.


/*
Change f1 Div innerHTML with object Technique???
<object id="foo" name="foo" type="text/html" data="aboutus.html"></object>
*/

var aboutus=document.getElementById('aboutus');
addEvent(aboutus,'click',function(){
var f1=document.getElementById('f1');
f1.innerHTML='<object id=articlehtml class=htmlpage type=text/html data=article.html></object>';
},false);

:stuck_out_tongue: You CSS the width and height of the object by class id or div id object in your main page div CSS?