javascript - Ajax JSON response not working -
i trying fetch json response django app response not working :
here 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) context.update({'contextlist':contextlist,'page_template': page_template}) if request.is_ajax(): # override template , use 'page' style instead. template = page_template return httpresponse(template, json.dumps(context), context_instance=requestcontext(request), content_type="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,status){ alert("data: " + context + "status: " + status); }, error: function( error ){ alert( error ); }, contenttype: "application/json; charset=utf-8", 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" %}
what want fetch server response , update contextlist
.... not working....
the problem you're facing you're trying update django template compiled variable called context_list
won't happen magically using ajax since django has precompiled html you're serving when hit page initially.
you can't circumvent can work around , below i'll show 2 ways of doing it.
your success()
handler in jquery script have manages search gets newly html you've recompiled you're not using anywhere ergo, won't work. in case you're logging stuff out console
. (this you're using option #2.)
you have 2 options see it. (it's lot of code i'll give pointers , not implementation, won't strip of fun!)
i'll give quick run down of both , can decide way want take.
- you can use jquerys
$.load()
method in order fetch recompiled template. - you can use
$.getjson()
, objects in json format , update html accordingly.
first option - $.load()
#django def search_view(keyword, request): search_result = searchmodel.objects.filter(some_field=keyword) t = loader.get_template("some_result_template.html") c = context({'search_results':search_result}) return render(t.render(c)) #jquery $("#result").load("url_to_your_search", { 'keyword': 'search_me' } );
second option - $.getjson()
#django django.core import serializers def search_view(keyword, request): search_result = searchmodel.objects.filter(some_field=keyword) json_data = serializers.serialize('json', search_result) return httpresponse(json_data, mimetype='application/json') #jquery $.getjson('url_to_your_search_view', { keyword: "search_me" }, function(json_data) { var items = []; $.each(json_data, function(key, val) { items.push('<li id="' + key + '">' + val + '</li>'); }); $('<ul/>', { 'class': 'my-new-list', html: items.join('') }).appendto('body'); });
now json code taken straight docs, have modify gist of what's needed in order yours work.
Comments
Post a Comment