To practice using jquery/ajax I decided to make my user list pagination use ajax. The code is below.
My first problem is that it only works for the first ajax request. It is programmed so that if the user has JavaScript turned off in their browser, it will still work just fine. But the ajax only works on the first request.
e.g:
open page 1 > press page 2 (uses ajax, works) > press page 3 (screws up, not ajax) > press page 4 (works again, uses ajax) > press page 5 (screws up again, not ajax)
The second problem is that some of the code returned by the ajax includes CHtml::linkButton's which tries to create JS in the ready() function. The problem is that the ready function is not returned in the ajax request (it is normally outputted above </body>), so the 'delete' buttons are not working.
Is there something simple I should do to fix this? any suggestion? And i'm dumbfounded as of why the ajax only works on the first requests.
I found out that If I put the pagination links OUTSIDE of the ajax (eg I put the pagination links outside of the div that gets updated with ajax), it works fine (as far as loading the content consistently).
I do not want this solution however as the pagination links wont update as I change pages.
But this gives me a clue to the problem: perhaps the jquery event do not work on updated content?? Is there something I am missing?
I was able to fix the ajax to work more than once. I moved the JS code into the ajax part of the view by using CHtml::script() instead of the CClientScript.
But I still have the problem of the JS not working for the 'delete' buttons (generated with the yiic tool). I understand the problem but can not think of a good solution without extending the paginator to dump the JS into the ajax view instead of CClientScript. Any thoughts?
I just found a better way of solving the "the ajax only works the first time" problem by using the jquery bind() function (i believe you could also use the live() functions).
jQuery(document).ready(function() {
function updatePage() {
$.post($(this).attr('href'), {}, function(page) {
$('#listPage').html(page);
$('.yiiPager a').bind("click",updatePage); //this is the new line
});
return false;
}
$('.yiiPager a').click(updatePage);
});
So now after it updates the content with the ajax return, it re-binds all the links with bind().