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

17.2k Views Asked by At

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?

4

There are 4 best solutions below

4
On BEST ANSWER

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);
0
On

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.

3
On

Try:

$('a.refresh').live('click', function(e) {
    e.preventDefault();

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

If the .refresh anchors are inside the #listdata element, then delegation is a more optimized solution:

var list = $('#listdata');

list.delegate('a.refresh', 'click', function(e) {
    e.preventDefault();

    $.ajax({
        url: '_js/data.php',
        success: function(data) {
            list.empty().html(data);
        }
    });
});
1
On

You'll need to change the href's on your links to <a href="#">...</a>. This prevents the browser from refreshing when you click the link.

If you're doing things this way, you'll also want to stick a "return false" at the end of the click handler to prevent bubbling.