Kotanet
Kotanet

Reputation: 573

Jquery function works only one time

here is a problem:

I need jquery to execute some php script and then return some results. There is a pagination at the page (generated by php). So there can be two cases. User gets to the page from external link => pagination starts from beginning. Or user selects a page => jquery runs php again and gets new pagination and results. Here is a script:

var page = '';
$.getJSON("test.php", {resid: "[[*id]]"}, function(output) {
    $('#testdiv').html(output.content).show();
    $('#pagination').html(output.pagination).show();
    $('a.pagenav').click(function() { 
        page = $(this).attr('href');
        $.getJSON("test.php", {resid: "[[*id]]", spp: page}, function(output) {
        $('#testdiv').html(output.content).show();
        $('#pagination').html(output.pagination).show();
        });
        return false;
    });
});

The script works at inilial load (pagination gets generated) and then one time I select a page. But the next time I select a page, it just follows it's url. Need help ) thx

Upvotes: 0

Views: 1261

Answers (1)

William Niu
William Niu

Reputation: 15853

The reason for your problem is that the next page you click no longer has the click handler bound. You need to bind the event to another element, that exists even after you load the new page. In your case, #pagination seems to be a good candidate.

var page = '';
$.getJSON("test.php", {resid: "[[*id]]"}, function(output) {
    $('#testdiv').html(output.content).show();
    $('#pagination').html(output.pagination).show();
});

$('#pagination').delegate('a.pagenav', 'click', function() { 
    page = $(this).attr('href');
    $.getJSON("test.php", {resid: "[[*id]]", spp: page}, function(output) {
      $('#testdiv').html(output.content).show();
      $('#pagination').html(output.pagination).show();
    });
    return false;
});

A less recommended approach (but easier to refactor your code to) is to use live(), which binds the event to the root element of the DOM tree.

$('a.pagenav').live('click', function() {
    ...
});

Upvotes: 1

Related Questions