[Django]-POST jQuery array to Django

47👍

You can try to use tasks[] instead of tasks as parameter when sending via ajax. Example:

$('.btn-group').find('#mark_as_done').on('click', function() {
    var tasks = grab_selected();

    $.ajax({
        type: 'POST',
        url: '/edit_lists/',
        data: {'tasks[]': tasks},
    });
});

Another thing is you are simply returning return tasks in edit_lists() view, you have return a HttpResponse instance or use shortcut like render:

from django.http import HttpResponse

def edit_lists(request):
    tasks = request.POST.getlist('tasks[]')
    return HttpResponse('Success')

Hope it helps,

12👍

You can try to use JSON.stringify() method instead of tasks as parameter when sending via Ajax.

Here’s the array data on my consol

enter image description here

Then send Array data by ajax

$.ajax({
     type: "POST",
     url: "/user/Survey-Design/",
     headers: {
         'Authorization': "Token " + localStorage.access_token
     },
     data: {
         'arr': JSON.stringify(arr)
     },
     success: function(result) {
         alert('Data Has been saved')
     }
 });

In views.py:

 def create(self,request):
     array_data = request.POST['arr']
     data = json.loads(array_data)
     print(data)
     return HttpResponse('Success')

Finally, show print(data) on terminal

enter image description here

Leave a comment