0

I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation. my code fetch don't work

ajax

  function myidLikeCom(params) {

    
      $.ajax({
        type: 'POST',
        url: '{% url "boards:likeComment" %}',
        data: {
          postid: params,
          csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
          action: 'post'
        },
        success: function (json) {
          document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']";
        },
        error: function (xhr, errmsg, err) {
  
        }
      });
    }

fetch don't work

  function myidLikeCom(params) {
        let data= {
          postid: params,
          csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
        }  
fetch('{% url "boards:likeComment" %}', {
    method: 'POST',
    body: data, 
})     
    }

1 Answer 1

1

Please see Django documentation for how to pass the CSRF token using AJAX.

You need to pass the token in the appropriate header.

    $.ajax({
        type: 'POST',
        url: '{% url "boards:likeComment" %}',
        headers: {
        'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val(),
        'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
        },
        data: {
          postid: params,
          action: 'post'
        },
        success: function (json) {
          document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']";
        },
        error: function (xhr, errmsg, err) {
  
        }
      });

Sign up to request clarification or add additional context in comments.

1 Comment

please convert this code to fetch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.