Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery append not sequentially adding div's when run from function

What I am trying to do is keep appending divs to #ajax_tweets when my ajax request returns a success. What currently happens is each time the ajax function is run on a timer and the ajax return a success the desired latest div is shown on screen correctly. However when it runs the next time the previous div is overwritten and not appended too. Either I am appending incorrectly, or I am not sure.. being driving me crazy for a while now.

Thank you in advance.

My code:

$(document).ready(function() {
    window.setInterval(ajax_test, 10000);
    counter = 0;

    function ajax_test() {
        $(".tweets").html('Retrieving...');
        $.ajax({
            type: "POST",
            url: "assets/ajax/get_latest_tweets.php",
            data: "tid=" + id,
            timeout: 20000,
            success: function(msg) {
                if (msg != "") {
                    add_to_tweet_feed( msg );
                    id++;
                    alert(id + msg);
                }     
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(".tweets").html('Timeout contacting server..');
            }
        });
    }

    function add_to_tweet_feed ( msg ) {
        $("#ajax_tweets").append(msg);  
    }
});

Code returned from server:

<div id="'.$tid.'" class="t_feed">             
                               <div class="calander right">
                                <div class="calander_month"><span>'.$row['pub_month'].'</span></div>
                                <div class="calander_day"><span>'.$row['pub_day'].'</span> </div> 
                               </div>
                                <span class="ajax_tweet bold">'.$row['source'].'</span>
                                <p>'.$tweet.'</p>
                              </div><div class="clear_both></div>

Front end code:

           <div id="ajax_tweets" class="tweets">

           </div>
like image 714
Cool Hand Luke Avatar asked Jan 27 '26 06:01

Cool Hand Luke


1 Answers

This line in your code actually clears out your whole container, that's why you only have the last one in there:

$(".tweets").html('Retrieving...');

One solution could be to make your markup something like this:

<div id="ajax_tweets" class="tweets">
    <div id="ajax_message"></div>
</div>

...and change your code to update that element and insert new tweets in front of it:

$(document).ready(function() {
    window.setInterval(ajax_test, 10000);
    counter = 0;

    var $message = $("#ajax_message");

    function ajax_test() {
        $message.html('Retrieving...');
        $.ajax({
            type: "POST",
            url: "assets/ajax/get_latest_tweets.php",
            data: "tid=" + id,
            timeout: 20000,
            success: function(msg) {
                $message.html('');
                if (msg != "") {
                    add_to_tweet_feed( msg );
                    id++;
                }     
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $message.html('Timeout contacting server..');
            }
        });
    }

    function add_to_tweet_feed ( msg ) {
        $(msg).insertBefore($message);
    }
});

Edit: Fixed a bug in the above code (bad usage of insertBefore()). Also, in case you're worried about the order in which your requests come back, you can add placeholders and replace them on success or remove them on failure:

$(document).ready(function() {
    window.setInterval(ajax_test, 10000);
    counter = 0;

    var $message = $("#ajax_message");

    function ajax_test() {
        $message.html('Retrieving...');

        var $placeholder = $('<div></div>').insertBefore($message).hide();

        $.ajax({
            type: "POST",
            url: "assets/ajax/get_latest_tweets.php",
            data: "tid=" + id,
            timeout: 20000,
            success: function(msg) {
                $message.html('');
                if (msg != "") {
                    add_to_tweet_feed(msg, $placeholder);
                    id++;
                }     
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $placeholder.remove();
                $message.html('Timeout contacting server..');
            }
        });
    }

    function add_to_tweet_feed (msg, $placeholder) {
        $placeholder.show().replaceWith(msg);
    }
});
like image 81
DarthJDG Avatar answered Jan 28 '26 19:01

DarthJDG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!