Med
Med

Reputation: 628

How to apply selector on ajax loaded content

I have a refresh() function, set to be called periodically this way:

setInterval("refresh()", duration);

In this refresh() function, I am dynamically prepending content into a HTML table.

So I have this simple table:

<table>
    <tbody>
        <tr><td>original title</td><td>original date</td></tr>
    </tbody>
</table>

That becomes this new table:

<table>
    <tbody>
        <tr><td>new title</td><td>new date</td></tr>
        <tr><td>original title</td><td>original date</td></tr>
    </tbody>
</table>

Through the action of this refresh() function:

function refresh() {
    var lastDate = $('.myTableClass > tbody > tr > td:nth-child(2)').first().text();

    $.get("./my_url.html?lastDate="+lastDate+, function (data) {
        if( data.trim().length > 0 ) {
            $(data).prependTo( $('.myTableClass > tbody') ).fadeIn('slow');
        }
    });
}

(The my_url.html page returns a simple <tr>....</tr> line.)

Everything works fine during the first call to refresh(), and new content is succesfully prepended to my table.

My problem is that after this first call, when there is no more new content to add, all the following calls to refresh() keep prepending the same content into my table.

So if I let the refresh being called 4 times, I am getting this table :

<table>
    <tbody>
        <tr><td>new title</td><td>new date</td></tr>
        <tr><td>new title</td><td>new date</td></tr>
        <tr><td>new title</td><td>new date</td></tr>
        <tr><td>new title</td><td>new date</td></tr>
        <tr><td>original title</td><td>original date</td></tr>
    </tbody>
</table>

I found out that this happens because the lastDate var is never correctly updated with the new line's date, it always contains the date from the original first line.

What am I missing here? How can I get the new date from the ajax-prepended first <tr> line of my table ? Is the way I select table > tbody > tr ... not compatible with ajax-loaded stuff?

[EDIT] If it's worth something, I am using jQuery 1.6.1.

Upvotes: 0

Views: 86

Answers (1)

Vishal Khode
Vishal Khode

Reputation: 841

You have to change the refresh function like this.

var lastDate = $('.myTableClass > tbody > tr > td:nth-child(2)').first().text();
function refresh() {
    $.get("./my_url.html?lastDate="+lastDate+, function (data) {
        if( data.trim().length > 0 ) {
           $(data).prependTo( $('.myTableClass > tbody') ).fadeIn('slow');
        }
    }).done(function(){
        lastDate = $('.myTableClass > tbody > tr:first > td:nth-child(2)').text();
   });
}

You need to use done() function, which gets called after your ajax request is completed and it'll give you the latest date..

Upvotes: 1

Related Questions