Jquery: Appending data to a div AFTER ajax load operation
15,414
Solution 1
putting append
inside callback function will work.
$('.container a').click(function(event) {
event.preventDefault();
$('#contents').remove();
$(this).parent().append("<div id=\"contents\"></div>");
$('#contents').html('<img src="/images/loading.gif" />')
.load('stuff.html',{},function(){
$(this).append('<div id=\"closebutton\"></div>");
});
});
Solution 2
Use the callback function [The function called when the ajax request is complete (not necessarily success)] for load and then append the content.
$('#contents').html('<img src="/images/loading.gif" />')
.load("stuff.html",function() { AppendContent(); } )
function AppendContent()
{
// do your append function here
}
Comments
-
Mala almost 2 years
I have a setup much like this:
$('.container a').click(function(event) { event.preventDefault(); $('#contents').remove(); $(this).parent().append("<div id=\"contents\"></div>"); $('#contents').html('<img src="/images/loading.gif" />') .load("stuff.html") .append("<div id=\"closebutton\"></div>"); });
However, the 'append' part seems to run before the load is completed, so that the closebutton div gets overwritten by the contents of stuff.html. How do I make it wait until the ajax operation has completed before performing the final append?
Thanks :)
Mala