Converting .ajax() to fetch() tutorial

I've been struggling with using JavaScript's fetch library to submit a form to my Django application. No matter what I try, it keeps throwing CSRF validation errors.

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 doesn't seem to work for me

  
function myidLikeCom(params) {
    let data = {
        postid: params,
        csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
    }

    fetch('{% url "boards:likeComment" %}', {
        method: 'POST',
        body: data, 
    })     
}

Answer №1

Check out the Django documentation to learn how to send the CSRF token via AJAX.

Ensure that you include the token in the correct 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) {
  
        }
      });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering difficulties while trying to include js-search in a Vue.js component

My current challenge involves importing the js-search npm module into a Vue component. However, whenever I attempt to do so using: import JsSearch from 'js-search' The subsequent console.log(JsSearch) statement returns undefined. To further in ...

Exporting Rendered HTML from a v-html Component in Vue

Utilizing the library sheetjs, I am generating HTML from an Excel range by utilizing the function sheet_to_html(). This generated HTML is then used to display a table using the v-html directive. Users can interact with the table by adding or removing class ...

unable to generate an object using factoryBoy class

I am attempting to create a class and make some instances, but I am encountering difficulties creating any instances with the class in my Django shell. factories.py import factory from webshare.models import WebShareFileFolders class WebShareFileFactory ...

Appreciation on Soundcloud

I am attempting to load my SoundCloud likes (formerly known as favorites), but I am facing issues with the ajax query not returning any results. The specific URL I am trying to load is: function retrieveSoundCloudTrackData(linkUrl) { var apiUrl = co ...

What is the most effective way to organize an array according to a key function that is computationally intensive?

After posting this question regarding sorting an array with a key function, it became evident that utilizing a comparison function was inevitable. The challenge at hand includes: Having a resource-intensive key function that needs to be transformed into ...

What happens if setTimeout fails due to a page error?

My current setup involves using setTimeout to refresh the page, updating the jQuery template items. Here is a snippet of the relevant code: <script type="text/javascript"> var results = JSON.parse('@svgPath'.replace(/&quot;/g ...

Purge POST request cache in Node.js

Currently, I have implemented nodemailer to enable users to contact me via email. Once the form data is submitted successfully, the page redirects to my homepage as intended. However, if an attempt is made to refresh the page, a confirmation alert pops up ...

What could be causing the User object in the auth0/nextjs useUser hook to have missing properties?

The user object retrieved using the useUser hook from auth0/nextjs package seems to be missing some important properties: { "nickname": "example", "name": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedbc6dfd3ced2dbfec7 ...

VueJS failing to display template content

After beginning the process of converting my Laravel 8 project to VueJS, I encountered an issue where the template content was not rendering properly. I followed these commands to incorporate the basic structure of Vue: php artisan ui vue && npm in ...

What is the process for connecting controls to Canvas sprites?

Any input is EXTREMELY helpful! To put it shortly, I'm in need of assistance with utilizing HTML5/CSS3 buttons to manage sprite animations on my canvas. These buttons are responsible for controlling the direction and speed of the sprites independentl ...

The issue of Three js object turning dark after implementing Phong Shading

I have a project where I am displaying 3 cubes and toggling between MeshLambertMaterial and MeshPhongMaterial when pressing the A key. However, I'm facing an issue where the object turns black when applying the phong shading, even though I've cal ...

In Vue JS, what is the best way to update a Child component after clicking a button on the Parent Component?

In my application, I have a setting option that updates from the Parent Component. The setting data is saved in localStorage and three Child Components utilize this setting data. <P> <c1> </c1> <c2> </c2> <c3> < ...

What does the single-threaded nature of JavaScript signify in terms of its intricacies and ramifications?

As someone relatively new to Javascript and JQuery, I recently discovered that Javascript operates on a single-threaded model. This has left me wondering about the implications it carries: What should be taken into account when writing JavaScript code? Ar ...

Function in Typescript used for checking types and catching compilation errors from external sources

Fact: I am currently using TS version 2.3.4. I have developed a function that checks if a variable is defined (it takes the parameter variable and returns 'undefined' !== typeof variable). It's quite simple. export function IsDefined(variab ...

Guide on implementing a globalThis polyfill within a NextJS application

Having some trouble with the Mantine react component library on older iOS versions. It's throwing a ReferenceError: Can't find variable: globalThis I've looked into polyfills, but I'm struggling to figure out how to integrate it into ...

How to Handle Overlapping Divs in HTML?

I have a sizable container div with various dynamic divs nested inside. These child divs are often padded to the left and contained within another div that is also padded on the left. My goal is to make the overall container div (which has a border) adju ...

Executing selenium tests on Internet Explorer 11 on a Windows 10 1809 machine without encountering any new pop-up windows

While testing on my computer, I encountered an issue where my test would start successfully, but after opening and closing several Internet Explorer windows during the test, no new windows would open. There were no error messages displayed, and the test se ...

What is the method to stimulate a browser refresh using programming?

In my setup, I have three computers with specific roles - the Server, Client, and Viewer. As the administrator, I have control over both the server and the viewer devices. When a user from the Client machine connects to the Server, they are greeted with ...

Is there a way for me to replicate the reloading problem that occurs when a button is clicked within an HTML

Recently, I encountered a problem with our company's Web product where pressing a certain button resulted in the entire page being reloaded. This issue reminded me of a similar situation described on this website. Following the solution provided there ...

How to interpret a collection of JSON string values received from C#

From my C# code, I am sending back a JSON array string that contains a list of classes. My goal is to extract the county element from each class and store it in a JavaScript array. Can you provide guidance on how to parse this string? {"d":"[{\"count ...