Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
how Convert .ajax() to fetch()

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, 
})     
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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) {
  
        }
      });

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!