I’m trying to create live search filter,with ajax
$(function() { $('#search-item').keyup(function() { $.ajax({ type: "GET", url: "/toysprices/", data: { 'query' : $('#search-toy').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { console.log(data); }
and my views.py
f request.method == "GET": search_text = request.GET['query'] if search_text: search_text = request.GET['query'] statuss = Status.objects.filter(status__contains = search_text) else: statuss = Status.objects.all() return render(request, 'ajax_search.html', {'statuss':statuss})
it works correctly, but it returns whole html page, how can i make to get only part which I want to render in my template.
Advertisement
Answer
Returning the result with JSON will solve your problem.
For Example,
# Django view
def search(request): if request.method == "GET": return_array = [] search_text = request.GET.get('query') # Always put request.GET.get('param') instead of request.GET['param'] if search_text: search_text = request.GET.get('query') statuss = Status.objects.filter(status__icontains = search_text) else: statuss = Status.objects.all() for i in statuss: return_sub_array = {} return_sub_array['status_name'] = i.status_name return_array.append(return_sub_array) return HttpResponse(json.dumps(return_array))
# Jquery function
$('#search-item').keyup(function() { $.ajax({ type: "GET", url: "/toysprices/", dataType: 'JSON', data: { 'query' : $('#search-toy').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: function(data){ if(data.length > 0 ) { console.log(data); for (var i = 0; i < data.length ; i++) { var obj = data[i]['status_name']; console.log(obj) // further logic goes here } } else { console.log("No result found"); } }, error:function(data){ console.log('error') console.log(data) } }); });