javascript - How to update Django endless pagination content list with new content with ajax response data -


i trying update page based on user search query. able search results server how update contextlist. have implemented django endless pagination how reload list new content

views.py

import json import traceback django.http import httpresponse django.template import context,loader django.template import requestcontext django.shortcuts import render_to_response escraperinterfaceapp.escraperutils import escraperutils   #------------------------------------------------------------------------------  def rendererror(message):     """         function displays error message     """         t = loader.get_template("error.html")                     c = context({ 'message':message})     return httpresponse(t.render(c))   def index(request,template = 'index.html',                   page_template = 'index_page.html' ):     """         function handles request index page      """      try:                 context = {}         contextlist = []         utilsobj = escraperutils()                 q = {"size" : 300000,              "query" :{ "match_all" : { "boost" : 1.2 }}}         results = utilsobj.search(q)                 in results['hits']['hits']:              contextdict = i['_source']                         contextdict['image_paths'] = json.loads(contextdict['image_paths'])             contextlist.append(contextdict)                      context.update({'contextlist':contextlist,'page_template': page_template})               if request.is_ajax():    # override template , use 'page' style instead.             template = page_template          return render_to_response(             template, context, context_instance=requestcontext(request) )      except :                 return rendererror('%s' % (traceback.format_exc()))  def search (request,template = 'index.html',                   page_template = 'index_page.html' ):      try:         if request.method == 'post':                      context = {}             contextlist = []             keyword = request.post['keyword']             print keyword                utilsobj = escraperutils()             results = utilsobj.search('productcategory:%(keyword)s or productsubcategory:%(keyword)s or productdesc:%(keyword)s' % {'keyword' : keyword})             in results['hits']['hits']:                 contextdict = i['_source']                 contextdict['image_paths'] = json.loads(contextdict['image_paths'])                    contextlist.append(contextdict)                          if request.is_ajax():    # override template , use 'page' style instead.                 template = page_template              context.update({'contextlist':contextlist,'page_template': page_template})                                    return httpresponse(json.dumps(context), mimetype='application/json')     except :                 return rendererror('%s' % (traceback.format_exc()))  #------------------------------------------------------------------------------      

index.html :

<html> <head>     <title>fashion</title>     <link rel="stylesheet" type="text/css" href="static/css/style.css"> </head> <body>  <form action="">     {% csrf_token %}     <input id="query" type="text" />     <input id="search-submit" type="button" value="search" />     </form>  <div class="product_container">     <ul class="product_list">         <div class="endless_page_template">             {% include page_template %}         </div>     </ul> </div>   <div class="product_container">     <ul class="product_list">         <div class="endless_page_template">             {% include page_template %}         </div>     </ul> </div>   {% block js %} <script src="http://code.jquery.com/jquery-latest.js"></script>  <script src="static/js/endless_on_scroll.js"></script> <script src="static/js/endless-pagination.js"></script>     <script>     $.endlesspaginate({paginateonscroll: true,     endless_on_scroll_margin : 10,     paginateonscrollchunksize: 5 });</script>  <script type="text/javascript">  $("#search-submit").click(function() {      // query string text field     var query = $("#query").val();     alert(query);         data = { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'keyword' : query};     // retrieve page server , insert contents     // selected document.         $.ajax({     type: "post",     url: '/search/',     data: data,        success: function(context){         var items = [];         var jsondata = json.parse(json.stringify(context));         console.log(jsondata['contextlist']);         $.each(jsondata['contextlist'], function(key, val) {         items.push('<li id="' + key + '">' + val + '</li>');         });         $('<ul/>', {         'class': 'product_list',         html: items.join('')         }).appendto('body');         },     error: function( error ){         alert( error );       },     datatype: 'json',     }); }); </script> {% endblock %}  </body> </html> 

index_page.html :

{% load endless %} {% paginate 10 contextlist %} {% item in contextlist %}     <li >         <a href="{{ item.producturl }}" ><img src="/images/{{ item.image_paths.0 }}/" height="100" width="100" border='1px solid'/></a>         <br>         <span class="price">         <span class="mrp">mrp : {{ item.productmrp}}</span>         {% if item.productprice %}<br>         <span class="discounted_price">offer price : {{ item.productprice}}</span>         {%endif%}         </span>     </li>   {% endfor %}  {% show_more "even more" "working" %} 

can please tell me how reload contextlist new data....


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -