Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery replaceWith to replace content of DIV only working first time

I'm using the following jQuery to pull new data and replace the contents of the DIV listdata

$(function(){
$('.refresh').click(function(event) {
    event.preventDefault();

    $.ajax({
        url: "_js/data.php",
        success: function(results){
            $('#listdata').replaceWith(results);
        }
    });
});
});

The script is triggered by numerous links on the page, such as:

<a href="" id="update1" class="refresh">Update 1</a>
<a href="" id="update2" class="refresh">Update 2</a>

For some reason the script only works on the first click of a link. Subsequent clicks do not refresh the data.

I've seen various fixes but nothing that I can get working. Any suggestions?

like image 246
Paul Avatar asked Feb 14 '11 17:02

Paul


2 Answers

It looks to me like your problem is with using replaceWith.

You're removing the element which matches $('#listdata') on the first call of replaceWith, so subsequent refreshes can't find where the data is supposed to be placed in the document.

You could try something like

 $('#listdata').empty();
 $('#listdata').append(results);

or chained like this

 $('#listdata').empty().append(results);
like image 124
Sam Dufel Avatar answered Nov 18 '22 09:11

Sam Dufel


If you're using replaceWith(), you're replacing #listdata with a brand new element altogether.

If data isn't something like <div id="listdata"></div> then #listdata is disappearing after the replaceWith(). I'm thinking you should probably use html() instead.

like image 31
Dominic Barnes Avatar answered Nov 18 '22 10:11

Dominic Barnes