Ajax POST, from html to views

Hello everyone,

I want to pass dicts of array to views.py with Ajax POST. But I cannot reach dictionaries in Array at views. Do you ahve any idea how to get them? Thanks in advance.

Output: In views.py, it prints empty array → [ ]

base.html

  <script>
      $(document).ready(function() {
         var arr = [];
         arr = [{0: '9', 1: '2019-03-15', 2: '2017-03-23', 3: 'Sputum', 4: 'MGIT'}, {0: '10', 1: '2019-03-15', 2: '2017-03-23', 3: 'Sputum', 4: 'LJ'}]
      }

      $.ajax({
            type: 'POST',
            url: '/rarecaseUpdate',
            data: {'new_arr[]': new_arr, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()},
          });
  </script>

views.py

@csrf_exempt
def rarecaseUpdate(request):
    if request.method == "POST":
        new_arr = request.POST.getlist('new_arr[]')
    
        print(new_arr)
    
        return HttpResponseRedirect("/")

I don’t think that you should access POST.getlist with “new_arr”, what happens if do “new_arr”?

2 Likes