How to append pages of data using jQuery and Django pagination? How to append pages of data using jQuery and Django pagination? ajax ajax

How to append pages of data using jQuery and Django pagination?


I'd show you with an example app. Since you're just learning, this will be helpful if you actually make one such app with the code below.

I've tried to keep the code as minimum as I could.

models.py

class Article(...):    title = models.CharField(...)    photo = models.ImageField(...)

views.py

import jsondef article_ajax(request):    TOTAL = 10    OFFSET = request.GET.get('offset', 0)    END = offset + TOTAL    # TOTAL means how many articles to load    # in a single request    # to understand OFFSET and END, consider this:    # mylist = [1,2,3,4,5,6,7,8,9]    # mylist[2:5] outputs => [3,4,5]    # Above 2 is OFFSET and 5 is END    articles = Article.objects.all()[OFFSET:END]    json_list = []    for article in articles:        json_list.append({            'title': article.title, 'photo_url': article.photo.url        })    data = json.dumps(json_list)    return HttpResponse(data, content_type='application/json')

urls.py

...url(r'^ajax/articles/$', 'myapp.views.article_ajax'),...

articles.html

The script also contains infinite scrolling code, too :)

<!-- All articles will be loaded in following div --><div id="ArticlesDiv"></div><script>var articleOffset = 0;var articleLoader = function() {    $.ajax({        url: '/ajax/articles/?offset=' + articleOffset,        success: function(data) {            if (data.length > 0) {                for (var i = 0, total = data.length; i < total; i++) {                    var compile_data;                    compile_data = '<h1>' + data[i].title + '</h1>\                        <img src="' + data[i]photo_url + '">';                    $('#ArticlesDiv').append(compile_data);                }                /* update the offset */                articleOffset += 10            } else {                $('#ArticlesDiv').append('No articles found');            }        }    });}/* Infinite scrolling for fetching articles */var $window = $(window);function prodScrollPosition() {    var distance = $window.scrollTop() + $window.height();    if ($('body').height() <= distance && $('#ArticlesDiv')) {        articleLoader();    }}$window.scroll(prodScrollPosition).scroll();/* Manually initiate the first ajax request */articleLoader();</script>


I will still use django-endless-pagination (Its the best ajax based pagination plugin out there), and the solution for your problem would be to recall the lightbox init after the pagination request completed, read more on callbacks:

<script type="text/javascript">    function hookup_lightbox(){        $( selector ).imageLightbox();    }    $.endlessPaginate({        onCompleted: function(context, fragment) {            // hookup lightbox            hookup_lightbox();        }    });</script>