Dictionary passed to js not working - javascript

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!

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.

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

Related

Panzoom on django with jquery

I have a really basic django app that displays .png images using django ImageField and ask the user to vote on different choices.
Now I need to make it interactive so that the user can also zoom and pan the images in the form.
I've downoad this github https://github.com/timmywil/jquery.panzoom and followed the instructions in my detail view: detail.html :
<div id="img">
<img src="{{question.image.url}}"/>
</div>
{% load static %}
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/dist/jquery.panzoom.js' %}"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("img").panzoom();
$("img").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") });
});
</script>
But nothing happens at all, the image is displayed in a fixed manner.
Previously I had some issues with 404 errors and now It seems to properly load the .js but It still doesn't work.
Thank you in advance for your help.
You have to have:
1) <script type="text/javascript" src="_path_to_your_JS_panzoom_file"></script> - to import that file
2)
<script type="text/javascript">
jQuery(document).ready(function(){
$(".panzoom-elements").panzoom();
// Pass options
$("a.panzoom-elements").panzoom({ minScale: 0, $zoomRange: $("input[type='range']") });
});
</script>
OR 2-b) Add those your code to a separate .js file and import it at the same way as in paragraph 1.
OK, finally I found the problem. The documentation is probably done for people who have a bit more background in that field! But of course other imports are required to make it work:
{% load static %}
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/test/libs/jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/dist/jquery.panzoom.js' %}"></script>
<script type="text/javascript" src="{% static 'polls/node_modules/jquery.panzoom/test/libs/jquery.mousewheel.js' %}"></script>
<section>
<div class="parent">
<div class="panzoom">
<img src="{{question.image.url}}">
</div>
</div>
<div class="buttons">
<button class="zoom-in">Zoom In</button>
<button class="zoom-out">Zoom Out</button>
<input type="range" class="zoom-range">
<button class="reset">Reset</button>
</div>
<script>
(function() {
var $section = $('section').first();
$section.find('.panzoom').panzoom({
$zoomIn: $section.find(".zoom-in"),
$zoomOut: $section.find(".zoom-out"),
$zoomRange: $section.find(".zoom-range"),
$reset: $section.find(".reset")
});
})();
</script>
</section>

codemirror - multiple text areas not working

As per the question here Can codemirror be used on multiple textareas?.
I have applied the exact config to my page and neither text areas are being converted to code mirrors.
there are no errors in the console either, im not sure what ive missed?
my code is as follows:
<script src="{% static 'home/scripts/codemirror/codemirror.js' %}"></script>
<link href="{% static 'home/scripts/codemirror/codemirror.css' %}" rel="stylesheet">
<script src="{% static 'home/scripts/codemirror/django/django.js' %}"></script>
<script type="text/javascript">
function editor(id) {
CodeMirror.fromTextArea(id, {
height: "400px",
continuousScanning: 500,
lineNumbers: true
});
}
editor('id_config');
editor('id_remote_config');
</script>
<form id="edit_template" action="" method="post">
{% csrf_token %}
{{ TemplateForm.template_name }}
{{ TemplateForm.config }}
{{ TemplateForm.remote_config }}
<input type='submit' value='Update' />
</form>
the django form renders the text areas with the IDs I have specified
anyone have any ideas?
Thanks
Those textareas don't exist at the time you call editor(). Either move your script tag below the form or call editor() inside a window load event handler

How to access to a javascript variable inside another html.twig file in symfony2?

I would like to know how to access to a javascript variable inside another html.twig file in symfony2. Let's assume that we have two html\twig files: file1.html.twig and file2.html.twig, their codes are as below:
The code of file1.html.twig:
<html>
<head>
<script>
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//here is some code
});
});
</script>
</head>
<body>
</body>
</html>
The code of file2.html.twig:
<html>
<head>
<script>
function f1(){
//here is the code that I need to access to the variable calendar of the file file1.html.twig
}
</script>
</head>
<body>
<form id="EventForm" action='{{path('ikproj_groupe_homepaeventsAdd',{id:idg})}}' method="POST" {{ form_enctype(form) }} onsubmit="f1();">
//here the body of the form
</form>
</body>
</html>
Actually, what I would like to know is how to access to the variable "calendar" of file1.html.twig inside the file file2.html.twig. So my question is it possible to do that??..If yes, how?
Put the code you want to share in a .js file:
// src/Acme/FooBundle/Resources/public/js/sharedCode.js
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//here is some code
});
});
Then just include the script everywhere you want:
<html>
<head>
...
</head>
<body>
...
{% javascripts '#AcmeFooBundle/Resources/public/js/sharedCode.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
</body>
</html>

Page turns blank when I try to show map using google's map api

When the user logs in I want to show a map.
The base html:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/static/main.css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=mykey&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-20, 110),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<title>myapp</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
mainpage.html:
{% extends "base.html" %}
{% block content %}
<div id="map-canvas"/>
{% endblock %}
When I load mainpage, the map doesn't show at all. I looked at the page source, which correctly showed <div id="map-canvas"/>, so the map is being loaded, but it isn't showing. Then I added some text
{% extends "base.html" %}
{% block content %}
<div id="map-canvas"/>
<div>derp<div>
{% endblock %}
derp also shows up in the source code but everything is still blank. What's wrong?
Your map-canvas div needs to be sized, as explained in the doc.
div is not a so-called empty element(like e.g. li, option , img), it requires a closing tag(also when it doesn't have any content):
<div id="map-canvas"></div>
That's the reason why you dont see "derp", for the issue with the map see the answer of bruno desthuilliers.

how to structure javascript files?

I have
base.html
pageA.html
pageB.html
pageA.js
pageB.js
pageA.js has code for pageA.html, pageB.js has code for pageB.html.
both pageA.js and pageB.js uses jQuery.
currently I am including all of the scripts in base.html, like so:
<html>
<body>
<div id="contents">
<!-- pageA.html / pageB.html comes here -->
</div>
<script src="js/jquery.js"></script>
<script src="js/pageA.js"></script>
<script src="js/pageB.js"></script>
</body>
</html>
I'd like to load pageA.js only for pageA.html and pageB.js for pageB.html, as the code in each file is not needed in the other page.
I've looked into requires.js library, but I'm not sure yet if it is the right solution for my problem. What are the best practices for structuring javascript files in this type of situation?
I think that the best you can do is add the <script src="js/pageX.js"></script> in the end of the pageX.html IF this page is loaded dynamically.
If the page isn't loaded dynamically, it may load before jquery.js and break you javascript.
Or you can read the current URL and load the correct script based on this info, like this:
var scriptPath;
var currentPage = window.location.pathname;
if (currentPage == "pageA.html")
{
scriptPath = "pageA.js";
}
else if (currentPage == "pageB.html")
{
scriptPath = "pageB.js";
}
var scriptElement = document.createElement("script");
scriptElement.setAttribute("type", "text/javascript");
scriptElement.setAttribute("src", scriptPath);
document.getElementsByTagName("head")[0].appendChild(scriptElement);
Do you have JavaScript to load in the contents of each html file? If so, and you have JavaScript code to run once each file is loaded you can call the required setup functions inside the load function like this:
base.html
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/pageA.js"></script>
<script type="text/javascript" src="js/pageB.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#loadPageA').on('click', function()
{
$('#contents').load('pageA.html', function()
{
setupPageA(); // defined in pageA.js
});
});
$('#loadPageB').on('click', function()
{
$('#contents').load('pageB.html', function()
{
setupPageB(); // defined in pageB.js
});
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a id="loadPageA">Load Page A</a>
<a id="loadPageB">Load Page B</a>
</body>
<html>
Or, you if you just want to run pageA.js when pageA.html is loaded in you can just include the pageA.js script element in page pageA.html itself, like this:
pageA.html:
<div id="pageAContent">Page A</div>
<script type="text/javascript src="js/pageA.js"></script>
pageB.html:
<div id="pageBContent">Page B</div>
<script type="text/javascript src="js/pageB.js"></script>
base.html:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#loadPageA').on('click', function()
{
$('#contents').load('pageA.html');
});
$('#loadPageB').on('click', function()
{
$('#contents').load('pageB.html');
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a id="loadPageA">Load Page A</a>
<a id="loadPageB">Load Page B</a>
</body>
<html>
The dynamic script src solution:
base.html:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function loadScript(script)
{
// Modify the existing script tag
if($('#dynamicScriptTag').length != 0)
{
$('#dynamicScriptTag').attr('src', script);
}
else // Create script tag
{
$('<script>').attr('type', 'text/javascript')
.attr('src', script)
.attr('id', 'dynamicScriptTag')
.appendTo('head');
}
}
$(document).ready(function()
{
$('#loadPageA').on('click', function(event)
{
event.preventDefault();
$('#contents').load('pageA.html', function()
{
loadScript('js/scriptA.js');
testScriptB(); // test if we can still call a function in scriptB.js
});
});
$('#loadPageB').on('click', function(event)
{
event.preventDefault();
$('#contents').load('pageB.html', function()
{
loadScript('js/scriptB.js')
testScriptA(); // test if we can still call a function in scriptA.js
});
});
});
</script>
</head>
<body>
<div id="contents"></div>
<a id="loadPageA" href="#">Load Page A</a>
<a id="loadPageB" href="#">Load Page B</a>
</body>
</html>
pageA.html:
<div id="pageAContents">Page A</div>
pageB.html:
<div id="pageBContents">Page B</div>
js/scriptA.js:
console.log($('#pageAContents').text());
function testScriptA(){ console.log('Can still call testScriptA!'); }
js/scriptB.js:
console.log($('#pageBContents').text());
function testScriptB(){ console.log('Can still call testScriptB!'); }
I ended up using Jinja(a template engine) to place the javascript files like following:
base.html
<html>
<body>
<div id="contents">
{% block contents %}
{% endblock %}
</div>
<script src="js/jquery.js"></script>
{% block scripts %}
{% endblock %}
</body>
</html>
pageA.html
{% block contents %}
..page A contents..
{% endblock %}
{% block scripts %}
<script src="js/pageA.js"></script>
{% endblock %}
If you are using a template engine, it could be a viable solution.

Categories

Resources