1

CSRF token missing - django/ajax Have already tried each and every solution proposed in this article but nothing seems to work for me. "CSRF token missing or incorrect" while post parameter via AJAX in Django

$(document).on('click', '.attendance_submit', function(){
          var urlname = '{% url "test" %}'
          var tableSel = $('.attendance_table tr:not(.group)');
          alert("DATA :"+html2json(tableSel));
          $.ajax({
            url : urlname,
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: {
              csrfmiddlewaretoken: '{% csrf_token %}',
              'TableData': html2json(tableSel)
              },
              
             success:
               alert('Attendance updated successfully')
          });
          return false;
        });   

PS: CSRF Token is also enabled in the form which I am using in this template, even tried removing from the form but to no avail.

1 Answers1

0

I was finally able to solve this problem using the below code @SeriForte 's answer pointed me in the right way when I was trying to troubleshoot some other issue. { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" }

$(document).on('click', '.attendance_submit', function(){
          var urlname = $(this).attr('data-url');
          var tableSel = $('.attendance_table tr:not(.group)');
          const csrftoken = 
          document.querySelector('[name=csrfmiddlewaretoken]').value;
          alert("DATA :"+html2json(tableSel));
          $.ajax({
            url : urlname,
            method: 'POST',
            headers:{
              contentType: 'application/json',
              'X-CSRFToken': csrftoken
            },          
            body: JSON.stringify(html2json(tableSel)),          
             success:
               alert('Attendance updated successfully')
          });
          return false;
        });