Adding a CSRF token for an Ajax request without utilizing jQuery

I am aiming to transmit data from my Javascript file to the views file within my Django app using an Ajax request. However, I am opting to utilize solely Javascript since I lack familiarity with jQuery and am uncertain of how to incorporate the CSRF token.

Below is the snippet of my Javascript Code:

    const request = new XMLHttpRequest();
        request.open("POST", "/list");
    var csrftoken = Cookies.get('csrftoken');

    let data = {
        items: JSON.stringify(items)
    }
    request.setRequestHeader( 'X-CSRF-TOKEN', csrftoken);
    request.send(data);

I have experimented using Cookies.get('csrftoken') as well as getCSRFTokenValue(), yet I am uncertain about how to proceed once obtaining the token.

The Developers' Console displays:

Failed to load resource: the server responded with a status of 403 (Forbidden)

Answer №1

In the absence of a form tag, you must include the csrf_token by adding a decorator right before your view code:

@csrf_exempt 
Def your_view(request):

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

Creating an HTML Canvas using an AngularJS template

I am facing an issue with rendering html elements on a canvas using html2canvas JS. I am utilizing AngularJS for data binding on the html page, but unfortunately, the dynamic data is not showing up on the canvas generated from these html elements. For inst ...

Ensure redirect is delayed until async data is fetched

Having come from the Angular world, I found it really easy and convenient to resolve data for routes. However, now that I'm using React, I'm unsure about how to achieve the same functionality. I would like to add an async data loader for my rout ...

"Data passed to a JavaScript callback function may result in an undefined

I've been experiencing some issues with callbacks and getting return data as undefined. function goodMorning(name, msg) { return `${name} ${msg}`; } function greet(name, msg, cb) { const myName = "Sairam"; console.log(`${cb(name)} ${cb(msg)} ...

Utilizing custom arguments with the filter function in Django QuerySet

While working with Django queryset filters, I encountered a situation where the arguments are provided like this: Model.objects.filter(name="Amit") Here, the column name and its corresponding value are obtained from the API request: def get(self ...

Unable to dispatch an event from a child component to a parent component in Vue.js

Within my parent component, I retrieve an array of strings from an API and pass it down to the child component. The child component then displays this data as a dropdown list. When an item is selected from the dropdown, I aim to assign it to a specific var ...

What is the process to insert a record into a table by triggering an AJAX call upon clicking "save

I'm looking to dynamically update a table with data from a database using AJAX. Specifically, I want the table to reflect any new records added by the user without having to refresh the entire page. Below is my JavaScript code snippet for handling thi ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

Entering numbers using <input type="number"> does not restrict invalid inputs, while accessing "element.value" does not give me the ability to make corrections

According to the MDN documentation on the topic of <input type="number">: It is said that they have built-in validation to reject entries that are not numerical. But does this mean it will only reject non-numerical inputs when trying to ...

Is it possible to place this script above all of my content?

For instance, take a look at this script: I am currently working on designing my own homepage and I would like to include the above script. The homepage will consist of links, buttons, and other content. However, I'm facing an issue where the birds f ...

Curious about why the .done() function is not receiving the jqXHR object?

var myRequest = $.ajax({ url: 'http://jsonplaceholder.typicode.com/posts/1', method: 'GET', }).done(function(response){ console.log(response); console.log(myRequest.responseText); }); Could it be possible that ...

Is there a JavaScript equivalent to the explode function in PHP with similar functionality

I'm facing an issue while attempting to split my string in JavaScript, here is the code I am using: var str = 'hello.json'; str.slice(0,4); //output hello str.slice(6,9); //output json The problem arises when trying to slice the second str ...

Error: React Beautiful D&D is unable to retrieve dimensions when no reference is specified

Hey everyone! I'm currently working on a meta form creator and having some trouble with performance issues. I created a sandbox to ask for help, but keep getting the error message "Cannot get dimension when no ref is set" when trying to drag a second ...

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...

Utilizing the Django try block efficiently

Is there an optimal way to verify the existence of a given course and chapter in the database before proceeding with the view logic: def Chapter_Detail(request,course_slug,chapter_slug): try: course = Course.objects.get(slug=course_slug) ex ...

Is it possible to create a Bootstrap 4 Modal using JQuery and AJAX?

Currently, I have a form enclosed within a modal, and I am struggling to extract the data from the modal for use in other parts of my application. Despite attempting to follow JQuery and AJAX tutorials to handle the data, I have been unsuccessful in getti ...

Setting a timed splash screen or image during a website's startup can be achieved by utilizing JavaScript and CSS

Is it possible to add an image or a splash screen for website startup in ASP.NET that automatically closes after 5 seconds and redirects to the main page? ...

Executing a jQuery.ajax call using a proxy server

I'm currently working on a Chrome extension and I have encountered an issue. When making a jQuery.ajax request for a standard HTTP page from a page served via HTTPS, Chrome blocks the request. This has led me to consider if it would be feasible to ret ...

Navigating through a JSON object created from a Python dictionary in JavaScript

When working on a django app, I have encountered an issue with returning JSON data on a jQuery ajax call: { "is_owner": "T", "author": "me", "overall": "the surfing lifestyle", "score": "1", "meanings": { "0": "something", ...

A comprehensive guide on harnessing the power of server-sent events in express.js

After incorporating the express.js framework, I configured my REST server. Now, I am interested in integrating server-sent events (sse) into this server. However, upon implementing the sse package from npmjs.com, an error occurs. It seems that the error is ...

What sets apart jQuery.ajax's dataType="json" from using JSON.parse() for parsing JSON data?

What is the difference between using dataType='json' and parsing response with JSON.parse(response) in jQuery Ajax? $.ajax({ url: path, type: 'POST', dataType: 'json', data: { block ...