Skip to content

I want to send list from javascript to django views.py

In this I want to send variable list[] to django. And I have tried many methods but I didn’t get how to pass this list to django plz help me to get rid of this. Thanku in Advance.

var list = [];
function add_item(item,next){
  list.push(item.name);
  item.parentNode.style.display = "none";
  next.style.display = "block";
  console.log(list);  }
function remove_item(item,prev){
  for (var i = 0; i <= list.length; i++) {
    if (list[i]===item.name) {
      list.splice(i,1);
    }  }
  item.parentNode.style.display = "none";
  prev.style.display = "block";
  }
$(document).ready(function() {
  $.ajax({
      method: 'POST',
      url: '/food_output',
      data: {'list': list},
      success: function (data) {
           //this gets called when server returns an OK response
           alert("it worked!");
      },
      error: function (data) {
           alert("it didnt work");
      }
  });
});

Answer

in modern style solution.you could do like this
I use django rest_framework here.this solution can submit more complex data to server.if you use modern library such as axios you even don’t need JSON.stringify()

$(document).ready(function() {
    list = [1,2,3,4]
    $.ajax({
        method: 'POST',
        url: '/food_output',
        contentType:"application/json",
        data: JSON.stringify({'list': list}),
        success: function (data) {
            //this gets called when server returns an OK response
            alert("it worked!");
        },
        error: function (data) {
            alert("it didnt work");
        }
    });
});
from django.http import JsonResponse
from rest_framework.decorators import api_view

@api_view(['POST'])
def food_output(request):
    print(request.data['list'])
    return JsonResponse({'success':True})

enter image description here