JS not functioning properly due to dictionary being passed incorrectly

Hello, I'm currently learning javascript and working on a django project. I've been trying to pass a dictionary template variable to javascript but have encountered some difficulties.

In my views.py file, the code looks like this:

def index(request):
   name={'bishal':509,'bishnu':510}
   return render_to_response("test.html",Context({'name':simplejson.dumps(name)}))

The test.html file includes:

{% load staticfiles %}
{% block include_js %}
<script src="{% static "js/chart.js" %}"></script>
<script src="{% static "js/test.js" %}"> </script>
{% endblock include_js %}

{% block main_content %}

    <script type="text/javascript" src="static/js/test.js"></script>
    <script type="text/javascript">
       var name={{name}};
    </script>
    <button class="btn btn-primary" id="btn1" type="button" onclick="myfunction()">1st visualization</button>
    {% endblock %}

The test.js file contains:

$(function myfunction() {
 document.getElementById('btn1').onclick=function(){
        name=JSON.parse(name);
        alert(name);
   };
});

However, an error message is displayed:

[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732

I also tried a similar approach in HTML:

<html>
<head>

<script type="text/javascript">
function myfunction()
{
    dict=JSON.parse(dict);
    alert(dict);

}
</script>

</head>
<body>

<script type="text/javascript">
var dict='{"bishnu": 509, "bishal": 510}';
</script>

<form>
<input type="button" 
onclick="myfunction()" 
value="Call function">
</form>

<p>By pressing the button, a function will be called. The function will alert a message.</p>

</body>
</html>

This method worked perfectly. Any assistance with resolving the issue would be greatly appreciated. Thank you!

Answer №1

Don't pay attention to the JavaScript code. The crucial line in your issue reads as follows:

[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732

The error code 404 signifies 'file not found' in HTTP, indicating that you are using an incorrect path for referencing your JavaScript file. Correct this mistake, and you might discover that your problem is resolved - or if not, it will at least present a different error.

Answer №2

Adrian made a valid point regarding the error message, however, my hunch is that the issue you are facing may be due to the absence of quotation marks around {{name}} in test.html. Give this a try:

<script type="text/javascript>
    var name='{{name}}';
</script>

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

The functionality of displaying the header when scrolling up and hiding it when scrolling down is not functioning as expected when using the

I am interested in implementing a scroll event to the window object that will display the header when scrolling up and hide it when scrolling down, but only after everything has finished loading. However, I am encountering an issue where sometimes the hid ...

Is there a way to prevent Django models from automatically adding the app's name to the model if the model name matches the app name?

So let me explain the situation: I have an application named vehicles with a model called Vehicles. However, when I run syncdb, it generates the table vehicles_vehicles. How can I modify this so that only the table vehicles is created? Furthermore, suppo ...

Guide on setting values for one-to-one fields in django

I am currently diving into the world of django and attempting to set a value for a one-to-one field in my models using manage.py shell. This is the approach I have tried, however, I am puzzled as to why it is not assigning the value to Author.address autho ...

What is the best way to display a message or alert after a page has been re

I've implemented Jquery Toastr to display success messages, functioning similarly to an alert for a brief period. My objective is to display a message after the page reloads. The issue arises when the page is reloaded, causing the JavaScript to reloa ...

Tips for launching server in debug mode with Pycharm

Having trouble debugging my code and setting breakpoints, as I am unable to start my server in debug mode. In my setup.sh file, there are multiple export statements with the last statement being 'python manage.py runserver'. I also added DEBUG = ...

Exploring Django: Form creation and managing many-to-many relationships with through relationships

I am currently tackling a specific issue related to a "many2many" relationship using the through specification. Despite attempting to utilize an inline_factory, I have not been successful in resolving the problem. Here are the tables involved: class Pers ...

Understanding how to extract inner text and splitting it can be a challenging task for developers when working with Javascript

Exploring the following basic html code: <div id="content"> This is a test </div> I am puzzled as to why this works: $(function(){ text = 'this is a text'; word = text.split(' '); alert(word[1]) }) while this does not: ...

Incorporating a Bootstrap Modal (Pop-up window) into the Navbar of a

How can I successfully integrate a Bootstrap Modal into my Django Navbar? Despite following the official Bootstrap documentation, I am encountering issues in my Django project. Is there a way to make this work? <!-- Button trigger modal --> <bu ...

Turn off the text cursor when inside a specific div block

Check out these two fiddles: fiddle 1 and fiddle 2 The only variation between the two is a single CSS property in .category -webkit-user-select: none; In fiddle 2, when you click and drag an element, the cursor remains as a pointer instead of changing t ...

Acquire the values of keys within a JSON array

As I work on iterating through a JSON array, I am aiming to extract the key values of each record within it. At present, my JSON object presents itself in the following structure: "users": { "key_11": { "text": "11" }, "key_22": { ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Unable to deactivate anchor links using jQuery... neither with "disabled" nor with e.preventDefault() while making an ajax request()

Currently, the only issue I am facing is disabling the anchor tag during processing. I have included an AJAX submit library which is functioning correctly. However, I am unable to disable the anchor tag using either "disable" or e.preventDefault(). I woul ...

How to use JQuery to set the margin-top of an element equal to the height of another element

I am attempting to create a website layout with a header at the top that has a dynamic height but remains fixed in position, followed by a content area. My initial approach involved adding a fixed padding-top to an element in order to display the content b ...

The Samsung Tablet is experiencing issues with numeric validation functionality

My numeric validation code is not working on Samsung tablets, although it works perfectly on other devices and browsers. $("#routingNum").keypress(function (e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > ...

Is there a way to identify the index of user input when using the .map method?

I'm currently utilizing the Array.prototype.map() method to present an array within a table. Each row in this table includes both an input field and a submit button that corresponds to each element from the Array.prototype.map() function. Is there a w ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

What could be causing the lack of content in my ajax multipart/form-data POST request body?

Having trouble with my HTML form and AJAX call: <form id="formid" action="upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> </form> Trying to send a file via POST request using AJAX: function upload_a ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

Disabling the onClick event on HTML tags with personalized WooCommerce messages

I have customized the notices/success.php template file by modifying the content as shown below: <?php foreach ( $messages as $message ) : ?> <div class="woocommerce-message" role="alert"> <span> <?php ...

Using THREE.js to create interactive clickable objects is a fun way to engage users. By clicking on a cube, you can trigger the appearance of a second cube,

I have a goal in mind. When the first box is clicked, I want a second box to appear. Then, when the second box is clicked, I want the color of the original cube to change. I've managed to achieve the first step, but I'm unsure how to implement th ...