What is the best way to store a JavaScript variable in Django's media folder?

I currently have a canvas on which I draw rectangles and save their coordinates. These coordinates are stored in a Javascript dictionary.

Through the script provided below, I am able to save/download a file containing the dictionary. However, it is only saved in the Downloads folder.

function myFunction() {
    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/text,' + encodeURI(JSON.stringify(dict));
    hiddenElement.target = '_blank';
    hiddenElement.download = 'dict.json';
    hiddenElement.click();
}

My goal is to save this file in Django's media folder specific to each user.

The desired location should be: media > {{user}} > dict.json

Any assistance on achieving this would be greatly appreciated.

Answer №1

Managed to resolve the issue by utilizing Ajax.

Here is the Ajax script:

$(document).ready(function() {
    $("#mybutton").click(function() {
        $.ajax({
            url: "{% url 'drawing' user %}",
            type: "POST",
            dataType: "json",
            data: {
                url: JSON.stringify(dict), // storing coordinates in dict
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
            success : function(json) {
                alert("Drawing saved!");
            },
            error : function(xhr, errmsg, err) {
                alert("Could not save drawing!");
            }
        });
    });
});

In views.py:

def drawing(request):
    user = request.user

    url = request.POST.get('url') // received URL from ajax will be stored here.
    first_value = next(iter(((request.POST).dict()).values())) // cleaning output
    
    with open("media/{}/dict.json".format(user), 'w') as draw:
        draw.write(first_value) // saving to file

    return JsonResponse(url, safe=False)

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

Randomly assigning a unique color to each div upon loading the page

I would like to create an effect where the background color of an icon changes randomly to match the color of the text. There are four predefined color choices available for this randomization. Here is the current code I am working with: HTML: <div ...

JavaScript: Accessing the selectedIndex of a dropdown list in RadGrid

Currently facing an issue with utilizing the RadGrid control from Telerik. I am attempting to access and manipulate the value of a GridDropDowncolumn within RadGrid using JavaScript (while in edit mode). Does anyone have any suggestions for the correct Ja ...

Warning: Promise rejection not caught in _.map function in NodeJs

Every time I run the code snippet below, I encounter an error - UnhandledPromiseRejectionWarning: Unhandled promise rejection. This issue is caused by either throwing inside an async function without a catch block or rejecting a promise without handling it ...

Is it possible to detect the source of a digest cycle in AngularJS?

I've found myself knee-deep in a legacy AngularJS project lately. The codebase is quite intricate and expansive, making it difficult to showcase here. However, I've come across an issue where functions triggered during digest changes are firing h ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...

Setting a default value for the longText field in Laravel

I have come across an issue in Laravel where I am unable to assign a default value to longText or text fields. Specifically, I am dealing with a field called "body" that will likely contain some text or HTML. How can I set a default value for this field ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Node: Exploring folders through recursive traversal

Node.js is a new world to me, and I'm determined to grasp its async behavior and callback structure. Here's where I'm currently struggling: // IMPORT ------------------------------------------------------------------------ fs = r ...

Transforming all commas to plus signs in a JavaScript codebase for the entirety of

Currently, I am using winston for logging and have created a common method to log throughout the project. However, I am facing an issue with many logging statements that look like this: logger.info("here is the data" , data) The problem arises when trying ...

Passing Variables to Child Components with Vue Slots

Imagine creating a button component with a variable named myVar: MyButton.vue <template> <div> <slot :name="text"> My Button </slot> </div> </template> <script> export default { name: 'm ...

Error: Type error - unable to call function on string during Ajax request

An error message saying "Uncaught TypeError: string is not a function" keeps popping up when I attempt to make an Ajax call. Here's the code snippet: $('input.js-nome-produto-servico').live("keyup", function(ed, h){ var $campo = ed.cur ...

Navigating to a parent URL where the Angular configuration is set can be achieved by following these steps

My application revolves around a webpage created with the use of node and angular. On the root URL (/), I have incorporated a signup and login form without the use of Angular. Upon successful login, Angular scripts and configuration files are loaded on the ...

Combining Context and MUI's theme provider for effective nesting: A step-by-step guide

Currently, I have a state set up to toggle between dark and light mode on a website that contains numerous nested components. The root App.js file looks like this: function App() { return ( <DarkModeProvider> ...

Display a comprehensive inventory of all bot commands within a designated category

When a user executes a command, I have various commands categorized and would like to present them accordingly. For instance, consider the following command: const Discord = require('discord.js') const { MessageEmbed } = require('discord.js& ...

Having trouble deciphering the API or a specific one from React.js/Node.js/Axios/Fetch?

I'm facing some confusion regarding my code. I have tried different APIs and some work, while others cannot be accessed in react.js. Can anyone help me correct this issue? The APIs that are not working in react.js always return a typescript fetching f ...

Disable touch interactions on the body, only allow pinch-zoom on specific elements

I have been attempting to implement the following code: body { touch-action: none; } .left-side { touch-action: pinch-zoom; } <div class="left-side"><img src="image.jpg" /></div> The touch-action: none is functioning properly, but ...

Encountering a 400 error message (Bad Request) when attempting to send a "POST" request via Ajax to a website built on the

I've been struggling to successfully create a "Post" using ajax. However, every time I attempt to do so, I encounter a "400 (Bad Request)" error. I am unsure whether the issue lies within the Rails website or my ajax request. The Rails setup is just a ...

Ways to access JSON data in JavaScript

I'm experiencing difficulty accessing the JSON data provided below. My approach involves utilizing the JavaScript AJAX success function, and when attempting alerts with the following code, $.ajax({ type:'GET', url:myURL, success : function ...

Assign a value of zero to the currentItem variable upon changing to a different category

Currently, I am developing a news application that utilizes a card-based layout for scrolling through news items. In the implementation, there is a variable called currentItem that keeps track of the current index being viewed. A recurring issue arises w ...

Encountering an issue with React npm causing errors that I am unable to resolve

Hey there, I'm a newbie to React. After setting everything up, I encountered an error after running "npm start." Can anyone help me figure out how to fix this? Thanks in advance! Click here for image description ...