Tisal
Tisal

Reputation: 155

Dictionary passed to js not working

I am new to javascript. I am working on django project. I need to pass the dictionary template variable to javascript and I have not been able.

views.py includes:

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

test.html 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 %}

test.js includes:

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

But error occurs saying:

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

I tried similar thing in html as:

    <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>

which worked perfectly. Please help!

Upvotes: 1

Views: 727

Answers (2)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

@Adrian is right about the error message, but I suspect that the problem you're thinking of is caused by not putting quotes around {{name}} in test.html. Try:

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

Upvotes: 0

Adrian Wragg
Adrian Wragg

Reputation: 7401

Ignore all the JavaScript. The key line in your problem is:

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

404 is the HTTP code for 'file not found', which means that you're using the incorrect path to reference your JavaScript file. Fix that, and you may find that your solution then works - or, if not, at least breaks differently.

Upvotes: 2

Related Questions