I am creating a phone-comparison project. I this when the user clicks the compare button a side nav will come out and he will add the products dynamically by clicking on the add button when the user is done with adding the products. then the user will click on another compare button for comparing the products and all the name of the products will go as an array to the views from the template.

now in views, the compare function will scrape the data on the basis of the array value and create a dictionary and render the dictionary to the demo.html.

but the problem is when I'm using XMLHttpRequest an Array is sent to the views and compare function is scraping the data but I can't use here render function Instead of it I'm returning JSONresponse.

but I don't know how to display the jsonresponse data in the template.

please help me to solve it. thanks in advance

the function which sends the array to views:

  function ComAction() {
     let xhr = new XMLHttpRequest(),
        data = new FormData();

    data.append('csrfmiddlewaretoken', getCookie('csrftoken'));


    brands.forEach(function (brand) {
        data.append('brand', brand);
    });

    xhr.open('POST', 'compare_in/', true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            data = JSON.parse(xhr.responseText);
            console.log(data);
            alert('Data received successfully. Brands are ' + data.brands);
            //var demo = xhr.base64.encode(JSON.stringify(data));
            //console.log('http://127.0.0.1:8000/demo/'+demo);
            window.location.replace(data.redirect_url);
        } else if (xhr.status !== 200) {
            alert('Request failed.');
        }
    };
  xhr.send(data);
}

in views:

 def compare(request):
   if request.method == 'POST':
    compare_res = request.POST.getlist('brand')
    .
    .
    .
     response_data = {
            'brands': d3,
            'redirect_url': 'http://127.0.0.1:8000/demo/'}
    return JsonResponse(response_data)
  return render(request, 'prodcutSearch/compare_in.html')

in urls:

  urlpatterns = [
   path('compare_in/', views.compare, name='compare'),
   path('demo/', views.demo, name='demo'),
  ]

0 Answers