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

EaselJS - Utilizing multiple canvases with varying frame rates

Currently, I am exploring EaselJS by creating two animation instances using sprite sheets on two separate canvases positioned at different locations but with the same z-index. The issue I am facing is that these instances are not layered properly. My setup ...

The function $.post(...) is failing to detect the JSON content in the

I am attempting to send a POST request to the server using the following code: var body = { PatientAgeFilter: { CompareOperator: parseInt(self.patientAge()), MoreThanVal: { AgeSpecifier: 0, AgeValue: parseInt(se ...

Packing third-party npm modules with Webpack for seamless integration

Description I am currently working on a project that involves nodejs, TypeScript, and express. The source files with a *.ts extension are being bundled using webpack, while the node_modules folder is excluded using webpack-node-externals. However, when I ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

Is it possible to change text dynamically with an input box using JavaScript?

Is there a way to use JavaScript to create two input boxes for text replacement? Instead of constantly editing code to replace different text, I am looking for a simple user interface with Input Box A, Input Box B, and a button. The first input box will ...

What measures can I take to restrict Node REPL instances from accessing the global scope?

When setting up a new repl instance in code, it automatically gains access to the global scope. While custom variables can be exposed in the local scope for the repl to utilize, restricting access to the global scope isn't straightforward. It would be ...

Looping through properties of objects with the help of angularJS ng-repeat is known as using objects['propertyname&#

What is the best way to iterate over an object with property names like this? $scope.myobjects = [ { 'property1': { id: 0, name: 'someone' } }, { 'property2': { id: 1, name: ' ...

How can we store data coming from PHP using AJAX and update the color of a div whenever new data is inserted?

Hey there, I'm currently working on a project where I need to save values and display them using Ajax after inserting them into a MySQL table using PHP. However, I'm having trouble with the alert function not working as expected. Let me share my ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

Incorporating a JavaScript object into a DataTables JSON structure: A practical guide

I have integrated the datatables jQuery plugin into my project and I am looking to streamline the process by creating a shared function to easily call a datatable from multiple pages without duplicating code. To achieve this, I am attempting to define the ...

Dynamic JavaScript Total Calculation

I have been struggling to update the total price for specific options. Even though the code was created by someone else and has worked fine for many users, I can't seem to make it work correctly. Any assistance would be greatly appreciated. Here is t ...

Converting an HTML page into a JSON object by scraping it

Is there a way to convert an HTML page into a JSON object using web scraping? Here is the content of the page: <html><head><title>Index</title><meta charset="UTF-8"></head><body><div><p>[ <a href ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

Can you explain Node.js and its applications as well as how it is commonly used?

A while back, during my time at IBM when I was immersed in learning, I came across something known as BlueMix, a cloud product. Within BlueMix, there was a rather primitive component called Node.js. Since that moment, I've been filled with curiosity a ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Encountering a problem with parsing a JSON object using the .map

After receiving this JSON response, my main goal is to extract the value located in the identifier. By utilizing console.log, I am able to analyze the structure of the object: Object {rows: Array[33], time: 0.015, fields: Object, total_rows: 33} fields: O ...

Display a loading animation before the page loads upon clicking

$("#button").click(function(){ $(document).ready(function() { $('#wrapper').load('page.php'); }); }); <div id="wrapper"></div> <div id="button">click me</div> I would like to display a loading ic ...

Issues with sending FormData through Ajax POST requests over a secure HTTPS connection

We are currently experiencing issues with uploading pictures to our server. The process works smoothly on http sites, but encounters errors on https sites. An error message is displayed: Failed to load resource: the server responded with a status of 500 ( ...

Displaying PHP content using JavaScript classes

I have a popup feature implemented in JavaScript and all the necessary scripts added to my HTML page. I am attempting to load a PHP page in the popup when the submit button of my form is clicked. The popup is functioning correctly for buttons like the one ...