Separate the JSON data into a new variable

I am working on a view called hero:

def hero(request):
  rfc='some value'
  depends_on=1234
  result_set = {'rfc': rfc, 'depends_on': depends_on}
  return HttpResponse(json.dumps(result_set))

Now, I want to pass the values of rfc and depends_on from this view to a template as JavaScript variables. This will allow me to use these variables to populate some fields in that template. How can I achieve this?

Your assistance is greatly appreciated.

Answer №1

If you are looking to incorporate ajax functionality, you can achieve this by following the code snippet below:

<script>
   var xhr=new XMLHttpRequest();
   xhr.open("GET","your_hero_url",true);
   xhr.onreadystatechange=function(){
      if(xhr.readyState==4 && xhr.status==200){
         var result_set=JSON.parse(xhr.responseText);
         console.log(result_set["key"]);
      }
   }
   xhr.send(null);
</script>

Additionally, for your views modification, consider the following:

def hero(request):
   result_set = {"key": "value"}
   return JsonResponse(result_set)

Answer №2

Accessing the Django context within JavaScript is made possible through the Django template tag.

const data = JSON.parse('{{ data|escapejs }}')

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

How can I personalize the color of a Material UI button?

Having trouble changing button colors in Material UI (v1). Is there a way to adjust the theme to mimic Bootstrap, allowing me to simply use "btn-danger" for red, "btn-success" for green...? I attempted using a custom className, but it's not function ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server. I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database? It is crucial that I prevent any possib ...

What are some effective methods for drawing attention to newly added table rows?

Whenever I input new data into my table, the data does not get highlighted as expected. However, the existing data in the table gets highlighted with no issues. Can you please help me troubleshoot why my code is not functioning correctly? Thank you. The f ...

The functionality of a Bootstrap popover with a form in data-content is fully operational within Django versions 1.11 and 2.0; however, it appears to encounter issues when utilized in

Below is the code that functions correctly in Django 1.11 and after upgrading also works in Django 2.0. However, it encounters issues in higher versions of Django starting from 2.1 up to 3.1.4. <button type="button" class="b ...

The loading indicator is not appearing inside the designated box

I have successfully implemented a loader using jQuery and CSS to display a gray background during an AJAX call. However, I am encountering an issue where the loader and background are being displayed across the entire page instead of just within a specific ...

Error message: NGINX combined with Express.js and socket.io, page not found

I currently have a node/express.js/socket.io application set up on an Ubuntu Server running on port 3002. I've made sure to open all ports on the machine for accessibility. When accessing the app directly at 11.111.111.1:3002/, everything runs smooth ...

Showing a React Portal Toolbar only when populated with children

OBJECTIVE: The objective is to show the ToolkitArea only when there are children present in "#toolkitArea". CHALLENGE: Unable to accurately determine the number of children inside the ToolkitArea. ACTIONS TAKEN SO FAR: I have developed a component calle ...

Extract JSON information using JavaScript or jQuery within the client's browser

I am looking to extract data on the client side by storing it in an input field after serializing it. JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer(); string jsonString = objJavaScriptSerializer.Serialize(_statusVal); jsonFmtStat ...

Oops! Looks like we encountered an error while trying to find the topics view for the board. The Board we're looking for doesn't seem to exist

I am a newcomer to the world of Python, specifically Django. I have been following the tutorials on simpleisbetterthancomplex.com but encountered an issue while testing my code. $ python manage.py test Here are my test results: System check identified 1 ...

Unable to retrieve the following element in a JavaScript array

I am a beginner in JavaScript and I am attempting to access the next element of an array using an onclick function but so far I have not been successful. var i, len; function quiz() { var quiz_questions = [ "who is the founder of Fa ...

Getting Creative with Jquery Custombox: Embracing the 404

Encountering a problem with jquery custombox version 1.13 <script src="scripts/jquery.custombox.js"></script> <script> $(function () { $('#show').on('click', function ( e ) { $.fn.custombox( this, { ...

Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema. const user = new mongoose.Schema({ username : Str ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Struggling with loading.jsx file in next js version 13.4.5?

Encountered an issue with loading components in next js 13.4.5 layout.jsx "use client"; import React, { Suspense } from "react"; import { ThemeProvider, createTheme } from "@mui/material/styles"; import CssBaseline from " ...

Updating a child component within a Modal: A step-by-step guide

I am using a global Modal component: export const ModalProvider = ({ children }: { children: React.ReactNode }) => { const [isModalOpen, setIsModalOpen] = React.useState(false); const [config, setConfig] = React.useState<ModalConfig | nu ...

Combining the total of numerous inputs that are multiplied by a specific value all at once

Hey, I've been working on a project with a table and an input field with costs using jQuery. You can check out This Fiddle for reference. $( ".total" ).change(function() { let i = 1; var input001 = document.getElementsByName(i)[0]; var ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Obtaining a String from a Nested Array through Nested Iterations

As someone who is just starting out with coding, I am currently focused on practicing loops and arrays. One of my exercises involves working with an array that contains multiple sub arrays, each of them consisting of pairs of strings. My goal is to extract ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...