Home > Back-end >  How can I send localstorage data from JavaScript ajax call and print return data from views in Djang
How can I send localstorage data from JavaScript ajax call and print return data from views in Djang

Time:01-17

I have stored some data on localStorage( Itemnames and ItemIds), now I want to send itemid's to django views from ajax. I have basics knowledge of django and learning Javascript. I tried to figureit out by myself but its been more than 4 days I could not succeed, any help will be highly appreciated.

My Javascript:

$(document).ready(function() {
    var compare = localStorage.getItem("comparisionItems");
    var compareObj = JSON.parse(compare);
    
    var data_url = window.location.href;
    console.log(compare)
    console.log(compareObj)
    
   
      
      $.ajax({
        url: './compare',
        type: "POST",
        data: {'compare_id': compareObj },
        headers: { "X-CSRFToken": $.cookie("csrftoken") },
        dataType: "json",
        success: function (data) {
            console.log(data)
            
        },
        error: function () {
            alert("Some problem on passing data");
        }
        
    });
});

After getting the localstorageitmes, the console return looks like this:

My views:

def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
    compare_id= request.POST.getlist('compare_id[itemIds]')
    """compare_id=request.POST.getlist('itemIds[]')  """
   
    """compare_id = request.POST.get('compare_id')"""
    product = get_object_or_404(Products, id=compare_id)
    context={ 'product':product}
   
    """ return render (request, './ecommerce/compare.html', context)"""
    return render (request, './compare.html', context)
else:
    context = None
    return render(request,'./compare.html', context)

How can I get the products which have id's pass by ajax? And is there any different ways to pass those products to the template or I can do it just like the regular Django context process?

CodePudding user response:

Pass json string from your ajax request.

$.ajax({
    url: './compare',
    type: "POST",
    data: JSON.stringify({'compare_id': compareObj }),
    headers: { "X-CSRFToken": $.cookie("csrftoken") },
    dataType: "json",
    contentType : "application/json",
    success: function (data) {
        console.log(data)
        
    },
    error: function () {
        alert("Some problem on passing data");
    }
});

And in your views.py

Get POST data first

 import json

data = json.loads(request.body)
compare_ids = data['compare_id'] if 'compare_id' in data else []
# since multiple ids may come you need to use `filter` 
products = Products.objects.filter(id__in=compare_ids)

CodePudding user response:

In your ajax you should stringify the data part like this:

 $.ajax({
    // rest of the code
    data: JSON.stringify({'compare_id': compareObj}),
    headers: { "X-CSRFToken": $.cookie("csrftoken") },
    dataType: "json",
    contentType: "application/json",
    // rest of the code
});

And then in you view:

import json

def compare(request):
   is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
   if is_ajax and request.method == "POST":
      compare_id = json.loads(request.POST.get('compare_id'))
      ids = compare_id.get('compare_id')
      # ids will be list of ids and you can get first id with index
      product = get_object_or_404(Products, id=ids[0])
      # rest of code
  •  Tags:  
  • Related