Sygon
Sygon

Reputation: 222

JQuery load() and .prepend()

Okay so I have the following code:

function() { 
$("ul#postbit").load('load.php').fadeIn("slow");
}, 3000);

What I am trying to achieve is after loading load.php to prepend the results in to <li> and have it fade in. At the moment it overwrites what is in ul#postbit. I only want it to load new results and keep what was in there. I hope that makes sense.

Upvotes: 1

Views: 7024

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

The .load() method is designed to work that way, i.e., to load the Ajax response directly into the element(s) that you call it on. Try instead using one of the other Ajax methods, e.g.:

$.get("load.php", function(data) {
    $(data).prependTo("#postbit").fadeIn("slow");
});

This assumes your "load.php" returns html including li elements, which is what you seem to be describing when you say your current code overwrites the existing list each time. If your "load.php" returns just the contents for a new li without <li> tags then you can create the li and prepend it:

$.get("load.php", function(data) {
    $("<li/>").html(data).prependTo("#postbit").fadeIn("slow");
});

EDIT: To have it continuously reload you could wrap the above into a function that you call with setInterval(), or do something like this:

function getMoreData() {
    $.get("load.php", function(data) {
        $(data).prependTo("#postbit").fadeIn("slow");
    }).complete(function() {
        setTimeout(getMoreData, 3000);
    });
}
getMoreData();

This uses setTimeout() to schedule another run of getMoreData() after 3 seconds, but it does so after the previous request completes.

Upvotes: 9

jared_flack
jared_flack

Reputation: 1646

You should check out the jQuery API. Here's the API for AJAX: http://api.jquery.com/category/ajax/

$.ajax({
    url: 'load.php',
    success: function(data) {
        $("ul#postbit").prepend('<li>'+ data +'</li>');
    }
});

Upvotes: 0

Related Questions