I am implementing vanilla JavaScript to send an AJAX post request to a Django server

I've been struggling with making an AJAX post request to Django using this JavaScript snippet:

const xhr = new XMLHttpRequest();

console.log(xhr.readyState);

xhr.open('POST', '');

var data = '{% csrf_token %}';

console.log(data);

console.log(typeof(data));

xhr.setRequestHeader('X-CSRF-Token', data);

xhr.onload = function(){

    console.log(xhr.readyState);

    console.log(xhr.status);

    if(xhr.status == 200){

        console.log(JSON.parse(xhr.responseText));

    }else{
        console.log("Something went wrong!!");
    }

}

xhr.send({'userId' : userId})

This is the error message I've been encountering: https://i.sstatic.net/2j05f.png

Unfortunately, I keep receiving a 403 forbidden error. Can anyone provide assistance?

Answer №1

This method will assist you in retrieving the csrf-token

function retrieveCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // Check if the cookie string starts with the specified name
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}

then:

const csrftoken = retrieveCookie('csrftoken');

to obtain the csrf-token.

It is also worth considering changing X-CSRF-Token

xhr.setRequestHeader('X-CSRF-Token', data);

to X-CSRFToken

xhr.setRequestHeader('X-CSRFToken', data);

I hope this information proves helpful

Answer №2

The {% csrf_token %} in the templates page translates to:

<input type="hidden" name="csrfmiddlewaretoken" value="WRWu3DwbdHDl1keRwSqUNrvcwZXqhCzkInEGVftyuwWG0v5kBBzeGrZ34wKpjFB5">

We must retrieve the CSRF token , which is the value of this element:

x = document.getElementsByName("csrfmiddlewaretoken")[0].value; 

After that, we have to provide this value to the setRequestHeader method of the JSON request, using "X-CSRFToken" as the first argument:

function requestJSON() {
         x = document.getElementsByName("csrfmiddlewaretoken")[0].value;
        jsonRequest = new XMLHttpRequest();
        jsonRequest.overrideMimeType("application/json");
        jsonRequest.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200 ) {
             var j = JSON.parse(this.responseText); 
             // handle the JSON data
             } 
         else {console.log(this.status);}
         };
        jsonRequest.open("POST","url/");
        jsonRequest.setRequestHeader("content-type","application/x-www-form-urlencoded");
        jsonRequest.setRequestHeader("X-CSRFToken",x);
        jsonRequest.send();
}

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

In search of the mean value using PHP, jQuery, and AJAX technologies

I have successfully created a star rating system using PHP and jQuery. The issue arises when attempting to display the average rate for a specific item that I am rating; instead, the average value printed is for all items being rated. Here is my jQuery co ...

What is the best way to update the current route in Angular 2 programmatically?

In my Angular 2 application, I am facing an issue with the navigation flow between the home component and the nav panel component. When a user clicks on the logout button in the nav panel, the current URL is correctly shown as "/login" in the console log. ...

Struggling to dynamically resize 2 boxes using JavaScript

I am attempting to create a layout with two Divs side by side, each containing slightly different content. I have successfully resized them equally using JavaScript, but the issue arises when loading the collapsed content as it does not adjust to the new s ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

"Enhance your Angular configuration with the powerful ngBootbox plugin

Is there a way to permanently change the locale of ngBootbox? I tried adding an extra angular configuration: var app = angular.module('some_module', ['highcharts-ng', 'ui.router', 'oc.lazyLoad', 'ui.selec ...

Why isn't my AJAX POST request to PHP functioning correctly?

It was all working perfectly fine earlier, but now something seems off and I must have made a mistake somewhere. I'm in the process of setting up a form where the information entered is sent via AJAX to my PHP file, which then outputs the username an ...

Preserve the location of a moveable div using jQuery

I have implemented draggable divs in my JSP page, allowing users to move them around freely. After dragging the divs, I would like to save their positions either in a cookie or database for future reference. Could you please advise on the best way to ach ...

What is the process for showing data in the input field once a value has been chosen in the select field

My goal is to have an input tag displayed in my modal after selecting an option from a select tag, with the data fetched from another table in the database. https://i.sstatic.net/kjoOZ.png totalfees.php if(isset($_POST["year"])) { ...

Encountering the "This field is required" error when trying to update an object in Django

I encountered an issue when attempting to update an object with an image upload via a form. The error message "This field is required" appears specifically when trying to modify the image of the object, even though creating the object works without any pro ...

Move the cursor to the end of the text when the key is released

I've developed a feature similar to that of a command line interface. When you input commands and hit the up key, the previous command is displayed. Everything is functioning as intended, but there's one minor issue. The current problem I'm ...

Fb.UI Dialogs now appearing in Popups rather than an iframe (part 2)

Here is a related issue that I came across: With the assistance of OffBySome, I managed to display my FB.ui dialog boxes in an iframe rather than as pop-ups. However, now I am experiencing an issue where the dialog appears but the loading throbber continu ...

What is the best way to modify the identifiers of the elements in the 2D matrix using JavaScript?

Hello, I've been working on a program that allows users to add or delete nodes at any index within a 2D array. However, I'm currently only able to retrieve the index of the clicked element, not all of them. How can I manipulate the IDs of this 2D ...

How can I transfer a particular data value from a div to JavaScript within Laravel 5.0?

Displaying separate square divs based on integers retrieved from the database. This is the front-end view. I want to pass the room ID (code) to a JavaScript function when clicking on these div elements. https://i.stack.imgur.com/aIYTr.png Below is my cur ...

What role does a promise play in rendering code asynchronous?

While we often use promises to avoid the dreaded function callback hell, a question remains: where exactly in the event loop does the promise code execute and is it truly asynchronous? Does the mere fact that the code is within a promise make it asynchron ...

PHP was unable to retrieve the values sent by AJAX

Hey there! I'm currently facing an issue with passing values from a link and using $_GET to retrieve those values. When testing it on my local environment, everything works fine. However, once I moved it to a live site, the parameters' values are ...

Is it possible to specify the input language for a textbox or textarea in a web form?

I am currently working on developing a website in Urdu language, with features similar to that of a blogging platform. To ensure that all posts are written only in Urdu, I am exploring different options. One idea I have is to use a Javascript code that ca ...

In nextjs, the page scroll feature stops functioning properly following a redirection

Currently, I am running on version 13.5.4 of Next.js In a server-side component, I am using the nextjs redirect function to navigate to another page. However, after the redirection, I noticed that the next page is missing the scroll bar and seems to be st ...

PHP-generated interactive pie chart

I'm encountering a puzzling issue while attempting to create a pie chart in Flot using data from PHP. The chart seems to be rendering incorrectly, and I'm struggling to identify the cause. Below is my PHP code (used for testing): echo json_enc ...

Struggling with implementing jQuery AJAX in Node.js Express - any tips?

Struggling with implementing ajax in node js for the first time. I've been testing it using the console, but unable to get a response. Here's my code: <script> function getMessage() { var data = $("#messageselect").val() $.ajax({ ...

Numerous ajax requests

I am utilizing a for-loop to make multiple ajax requests: for(var o = 1; o <= 2; o++) { $.ajax({ type: 'GET', url: 'lib/terrain.php', ...