dimanche 3 mai 2015

Load ajax data while page scroll is being done in Django python

I'm trying to load data from database table upon page scroll down using Ajax in DJango 1.7 and Python27, it loads everything during initial load itself.. Please help me to fix this issue.

Views.py :

def table_row(request, start=0, count=35): #set count here for how many ticket to load each call. Set it so it loads slightly more than enough to fill a page. 
if request.method == 'POST':
     filter =  request.POST.get('category', False)
if filter:
     tickets = Ticket.objects.filter(category=filter)
else:
     tickets = Ticket.objects.all()
start = int(start)
return render_to_response('table-view.html',
     {
             'tickets':tickets[start:start+count], #slices the index of tickets to return
     }, RequestContext(request))

table-view.html :

<script type="text/javascript">
var processing;
function loadTickets(){
 //the ajax call to load more tickets into the table
 var ticket_count= $('tr.ticket').length; //grabs the number of data results returned
 $.ajax({
      type:'post',
      url:'{% url 'app.views.table_row' %}'+ticket_count+'/'+,
      data:{
           'csrfmiddlewaretoken':getCookie('csrftoken'), //This is the ajax csrf protection function 
      },
      success:function(data){
           $('#text-loading').toggleClass('hidden',true); //hides the loading animation when ajax call returns tickets
           $('#table-body').append(data); //adds data to the end of the table
           processing = false; // the processing variable prevents multiple ajax calls when scrolling
      }
 });

}

$(document).ready(function(){
loadTickets(); //initial ticket load
 $('#main-window').scroll(function(e){
      if (processing){
          return false;
      }
      if ($('#content-window').scrollTop() >= ($('#full-table').height() -$(#'content-window').height())){
          processing = true; //prevent multiple scrolls once first is hit
          $('#text-loading').toggleClass('hidden', false); //show the loading animation
          loadTickets();
      } 
 });

});

In the same file, I'm populating the data using below :

<td>{{ ticket.id }}</td>
<td>{{ ticket.title }}</td>
</tr>
{% endfor %}
<!--The loading animation. Appears on first page load and every time the   scrolling reaches the bottom -->
 <div id='text-loading'> We are loading more tickets

I'm suspecting $('tr.ticket').length in ajax function which I'm not sure about.. what it is.. may be I need to find someway to use django convention in assigning number of data results? please help me on this.. Thanks

Aucun commentaire:

Enregistrer un commentaire