views:

988

answers:

2

Hi

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

+3  A: 

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
}
rahul
+5  A: 

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>");
               });
});
Anwar Chandra
thank you this worked perfectly
Mala