Best Practices for Retrieving Data with Django - Post Requests

I'm attempting to use Ajax to send a JavaScript array to Django. Here's my code:

document.getElementById('input-generate').onclick = () => {

    // Get the token
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    // Create new request add token 
    const generateRequest = new XMLHttpRequest();
    generateRequest.open('POST', '/generate');
    generateRequest.setRequestHeader('X-CSRFToken', csrftoken);

    generateRequest.onload = () => {

        console.log('generateRequest');

    };

    // Add the motif to send with the request
    const data = new FormData();
    console.log(notes);
    // [{…}] 0: {duration: "4", note: "E4", dot: false} length: 1 __proto__: Array(0)
    data.append('motif', notes);

    // Send request
    generateRequest.send(data);
};

In views.py:

@require_http_methods(["POST"])
def generate(request):

    # See if method was post
    if request.method == "POST":

        # Retrive seed
        seed = request.POST.get("motif")
        print(seed)
        print(type(seed))

        # Sanity check
        if not seed:
            return JsonResponse({"succes": False}, status=400)

        # Return the seed
        return JsonResponse({"seed": seed}, status=200)

However, when I print out seed and its type, all I get is:

[object Object]
<class 'str'>

How can I display the actual array being sent?

By the way, the array I'm sending contains strings encoding notes, for example:

notes = [{duration: "4", note: "E4", dot: false}, {duration: "8", note: "D4", dot: false}, {duration: "2", note: "F4", dot: false}]

Answer №1

It is important to remember to use JSON.stringify on your notes array before sending it, especially when the content-type is form-data. This way, Django will be able to parse the incoming JSON in your view.

Here are some example changes you can make to your JavaScript code:

document.getElementById('input-generate').onclick = () => {

    let notes = [{duration: "4", note: "E4", dot: false}]  // sample data

    // Get the token
    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    // Create new request and add token 
    const generateRequest = new XMLHttpRequest();
    generateRequest.open('POST', 'http://127.0.0.1:8000/watchdesk');
    generateRequest.setRequestHeader('X-CSRFToken', csrftoken);

    // Add the motif to send with the request
    const data = new FormData();
    console.log(notes);
    data.append('motif', JSON.stringify(notes));  // stringify notes

    // Send the request
    generateRequest.send(data);
};

I have tested this and found that it works without making any changes to the view.

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

Showing a loading animation inside an HTML element

I have a main webpage that contains several buttons. Each button, when clicked, loads a specific target page as an object within a div on the main page. The "target" refers to the page that will be displayed within the object. <script> .... chec ...

When a radio button is checked, add a class to its parent element that has a specific class assigned to it

In order to dynamically add a class to a specific div element higher up the DOM hierarchy when a radio button is clicked, I am in need of assistance. There are multiple instances of these div elements with different radio buttons, so it is crucial that on ...

add the elements of an array to multiple div elements sequentially

I'm attempting to update all titles in .item with the values from array. The array I am using contains the following elements: var itCats = ['one', 'two', 'three', 'four']; Additionally, this is the HTML struc ...

How can I assign several Objects to a single array?

My goal is to save several objects into an array. Specifically, I have five objects named obj1, obj2, obj3, obj4, and obj5. ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

Stop automatic form submissions from the enter key

My live chat messaging system is experiencing an issue where the page refreshes every time a user presses the enter button. I attempted to use prevent default code, but it did not work for me. I'm new to website programming, so if there are any proble ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...

Trouble with closing Bootstrap 4 modal

My Bootstrap 4 modal is causing issues as it pops up on button click but won't close unless I refresh the page. I've been attempting to get it to close by clicking the 'close' button or simply by clicking anywhere on the main page body. ...

retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem ...

Looking for suggestions on how to bring this idea to life

I'm searching for a solution using JavaScript, jQuery, or Angular. I've created three random arrays like this: for example: (The values are randomly generated from the array ['member', 'medical', 'rx', 'disabi ...

Reading an XML file to locate items nested within the same bracket

Within my JavaScript function, I am utilizing the following code to extract data from an XML file: var title = $(this).children('Title').text(); This snippet of code successfully retrieves the content under the <Title> tags: <Title> ...

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

How can Reactjs access a configuration file?

I am struggling to find a solution for reading a properties file in reactJS. I have come across the "properties-reader" module but I can't figure out how to make the require function work. Is there an easier way? For instance, import React, { Com ...

Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? ...

retrieving data from identical identifiers within a loop

Within my while loop, I am retrieving various dates for each event. <?php while( have_rows('_event_date_time_slots') ): the_row(); ?> <div> <h3 class="date-<?php echo $post->ID?>" name="tttdate<?php e ...

Utilizing jQuery and ajax to invoke an MVC controller

Hi there, I am currently facing an issue with calling a method in my controller using ajax and jquery with parameters Controller: [HttpPost("{Id}")] public ActionResult PostComment(int Id, ShowViewModel model) { } View: I have a button named AddCommen ...

Axios failing to transmit cookie information, despite setting withCredentials to true

Exploring the capabilities of React and Express to handle requests while including cookies. The communication between client-side and server-side is successful, however, the cookies are not being transmitted. On the client-side: import axios from 'axi ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

Establishing the default selection and deactivating the notification

I've been struggling for a while to make this function properly. My knowledge of jquery and javascript is limited, so I'm facing some challenges. What I'm aiming to do is to have a default option selected from the drop-down menu when the but ...