JQuery content from loop appends last

118 Views Asked by At

Basically I need to append a header, content and footer message.

The content comes from a loop and for some reason it appends last.

    function sendMail(){

    $("#textareaContainer").append('<textarea id="someTextarea" rows=12 class="span7">Some header text that is needed</textarea>');

    for (var i=0;i<idToUse.length;i++){
        $.post("actions.php", "do=contentFromPhp"+"&id="+idToUse[i],0,"json").done(function(result) {
        for (var i=0;i<result.length;i++){
        $("#someTextarea").append("\r"+result[i].theContent);
        }
    idToUse = [];
    });

    }
    $("#someTextarea").append("\rSome footer text that is needed!");

}

The current output is:

Some header text that is needed
Some footer text that is needed!
Content From loop 1
Content From loop 2

I need it to be:

Some header text that is needed
Content From loop 1
Content From loop 2
Some footer text that is needed!
2

There are 2 best solutions below

0
On

It is because you are using ajax to fill the data, Note: Even this may not give the exact result since the ajax requests may comeback in different order

function sendMail(){

    $("#textareaContainer").append('<textarea id="someTextarea" rows=12 class="span7">Some header text that is needed</textarea>');

    var xhrs = [], xhr;
    for (var i=0;i<idToUse.length;i++){
        xhr = $.post("actions.php", "do=contentFromPhp"+"&id="+idToUse[i],0,"json").done(function(result) {
            for (var i=0;i<result.length;i++){
                $("#someTextarea").append("\r"+result[i].theContent);
            }
            idToUse = [];
        });
        xhrs.push(xhr)
    }

    $.when.apply($, xhrs).then(function(){
        $("#someTextarea").append("\rSome footer text that is needed!");
    })

}
0
On

You need to append the footer in the AJAX callback function:

for (var i=0;i<idToUse.length;i++){
    $.post("actions.php", {
        do: "contentFromPhp",
        id: idToUse[i]
    }, 0, "json").done(function(result) {
        for (var i=0;i<result.length;i++){
            $("#someTextarea").append("\r"+result[i].theContent);
        }
        $("#someTextarea").append("\rSome footer text that is needed!");
        idToUse = [];
    });
}

I also changed your data from a string to an object, so that jQuery will URL-encode it properly.