0

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'),
  ]
  • Instead of redirecting on Ajax success, you should insert the value of `data.brands` into your current page. You haven't given enough information on the structure of the page or the content of that variable to help any further, though. – Daniel Roseman May 13 '19 at 08:33
  • you're on the right track. In your success function for the xhr request (where you now do `alert('Data received successfully')`, you just need to dynamically add the data to the divs you want to update (and remove the redirect `window.location.replace(...)`.) – dirkgroten May 13 '19 at 08:34
  • how? please edit your suggestion in my code – sourav kukreti May 13 '19 at 08:36
  • @dirkgroten what I write in place of window.location.replace? – sourav kukreti May 13 '19 at 08:37
  • 1
    Learn how to manipulate the DOM in javascript, e.g. [this tutorial](https://medium.freecodecamp.org/dom-manipulation-in-vanilla-js-2036a568dcd9) or using jquery like explained [here](https://learn.jquery.com/using-jquery-core/manipulating-elements/) – dirkgroten May 13 '19 at 08:40
  • @dirkgroten I want the JsonResponse data in demo template not where i am – sourav kukreti May 13 '19 at 08:43
  • @souravkukreti you can either use [sessions](https://docs.djangoproject.com/en/2.2/topics/http/sessions/) to store data between views or save results in database for future use. – Gasanov May 13 '19 at 08:52
  • @Gasanov how to store data in sessions. please help me – sourav kukreti May 13 '19 at 08:56
  • There is literally [examples](https://docs.djangoproject.com/en/2.2/topics/http/sessions/#examples) section in the page I linked. – Gasanov May 13 '19 at 08:59
  • @souravkukreti then why do you post the data using ajax? Just post your form normally to a view that renders the template you want, without using javascript. It doesn't make sense posting with ajax first just to redirect, and having to keep the data using a session. – dirkgroten May 13 '19 at 09:12
  • @dirkgroten Because I'm creating a dynamic list using javascript and adding it to an array. If I were sending only one data then surely I would use the form. – sourav kukreti May 13 '19 at 10:10
  • In that case you should just add the data using javascript when the `on('submit')` event of the form is triggered. See [this question](https://stackoverflow.com/questions/993834/adding-post-parameters-before-submit) for example. This way, you just change the data but still submit the form normally, without xhr. – dirkgroten May 13 '19 at 10:19

0 Answers0