Javascript enabling buttons works in JSFiddle but not in browser - Flask - javascript

I am using Python/Flask to develop a web app.
In a page I want to have some buttons disabled initially, and then enabled if a function is called.
In JSFiddle for example something like this works:
JSFiddle
However, if in my index.html file I have something like this:
{%- extends "base.html" %}
{% import "bootstrap/utils.html" as utils %}
{% block content %}
<h1>Three buttons!</h1>
<div id="audio">
<p>
<button id=startRecord onclick="startRecording()">Start</button>
<button id=stopRecord onclick="stopRecording()">Stop</button>
<button id=submitRecord onclick="submit()">Submit</button>
</p>
<p>
<audio id=recordedAudio></audio>
</p>
<p>
<a id=audioDownload></a>
</p>
</div>
{% endblock %}
{% block scripts %}
<script src="{{url_for('static', filename='js/recordtest.js')}}"></script>
{% endblock %}
Where recordtest.js is:
startRecord.disabled = false;
stopRecord.disabled = true;
submitRecord.disabled = true;
function startRecording() {
stopRecord.disabled = false;
}
All buttons start as enabled and are not changed with the function.
I am using Chrome.

Put following lines in your js files in a self executing javascript closure, something like written below.
$(function(){
startRecord.disabled = false;
stopRecord.disabled = true;
submitRecord.disabled = true;
function startRecording() {
stopRecord.disabled = false;
}
})();
Also, put type="text/javascript" in script tag for neatness.

Firstly put an alert in startRecording function to confirm that it is actually getting called, try the code like this
document.getElementById("startRecord").disabled = false;
document.getElementById("stopRecord").disabled = true;
document.getElementById("stopRecord").style.backgroundColor = '#aaa'; // or any color you need to make it look like its hidden
document.getElementById("submitRecord").disabled = true;
document.getElementById("submitRecord").style.backgroundColor = '#aaa'; // or any color you need to make it look like its hidden
function startRecording() {
alert();
document.getElementById("stopRecord").disabled = false;
document.getElementById("stopRecord").style.backgroundColor = '#FFF'; // or any color you need to make it look like its not hidden
}
Also Verify that your java-script files are properly linked, that's probably the cause

Related

Refresh html DIv in Django

i am trying to refresh an {%extends%} page since my base.html is getting message information from whatever is happening in the python backend, it only shows the message after i refresh my page and i want to refresh it every x seconds so the alerts will show without needing to refresh my entire page.
<div id="Mydiv">
{% extends 'crodlUSDT/base.html'%}
</div>
<script>
$(document).ready(function()
{
function refresh()
{
var div = $('#Mydiv'),
divHtml = div.html();
div.html(divHtml);
}
setInterval(function()
{
refresh()
}, 3000); //300000 is 5minutes in ms
})
</script>
this is what i've found online but tested a lot of different things but none are working, is this possible ?
thanks
ive also tried doing this inside of my html file
<div id="messages" class="messages">
{% if messages %}
{% for message in messages %}
<div class = "alert alert-{{message.tags}}">{{message}}</div>
{% endfor %}
{% endif %}
</div>
<script>
$(document).ready(function()
{
function refresh()
{
var div = $('#messages'),
divHtml = div.html();
div.html(divHtml);
}
setInterval(function()
{
refresh()
}, 3000); //300000 is 5minutes in ms
})
</script>
but also only shows the message after page refresh

Passing context variable from template to JavaScript file

This thread here discussed using variables in inline JavaScript in templates. If I have separate .js files containing scripts, sitting in static folder, such as following:
utils.js
const createButton = (buttonCount) => {
containerId = "myContainerId"
container = document.getElementById(containerId)
for (var i = 0; i < buttonCount; i++) {}
newButton = document.createElement("button")
newButton.value = "Test"
newButton.id = "testButton" + i
container.appendChild(newButton)
}
}
createButton(buttonCount)
mytemplate.html
{% extends "base.html" %}
{% load static %}
{% block title %}Testpage{% endblock %}
{% block content-main %}
<link href="{% static "css/mycss.css" %}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" />
<div id="myContainerId"></div>
<script src="{% static 'js/utils.js' %}"> </script>
{% endblock %}
If I have a variable buttonCount passed into this template via a view function's context, how do I pass it to the utils.js file to be called by function createButton()?
views.py
def button_view(request):
...
buttonCount = 5
return render(request, 'mytemplate.html', {'buttonCount': buttonCount})
There can be a few ways:
Using Input Field
<input id="buttonCount" value = "{{buttonCount}}" style="display:none;">
Then read value of element with id= buttonCount in utils.js.
Inline Script **Not Suggested,Use Document.onload instead.
<script>
set_button_count({{buttonCount}});
</script>
But this will create a problem when your utils.js is not loaded yet.
document.onload
Place the script source in <head></head>
<script src="{% static 'js/utils.js' %}" defer> </script>
<script>
document.addEventListener('onload',function(
{set_button_count({{buttonCount}});
})
</script>
set_button_count() is to be placed in utils.js
Defer will ask browser to only fire document load when utils.js
is complete and it will be fetched and loaded after the document is
loaded.
Warning: Inline scripts are to be used with strict CSP (Content Security Policy).Any inline script can be given a src as nonce.
CSP can be done on Server Side on apache or Nginx which are very common web server/reverse proxy or you can also mention the same in HTML if you don't have control on that.
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' 'nonce-{{nonce}}';">
and this nonce can be generated something like this:
import random,base64
def usersession_processor(request):
user = request.user
unbaked_nonce = '%32x' % random.getrandbits(16*8)
unbaked_nonce = unbaked_nonce.encode('utf-8')
baked_nonce = base64.b64encode(unbaked_nonce)
baked_nonce = baked_nonce.decode('utf-8')
Then <script src="{{nonce}}"></script> can be used for safe inlines.
I don't think this is recommended but you could do something like this if you're using the django template context. Put the script at the bottom of the page and include the buttoncount as a Django Templating Language variable. I don't think it's recommended to mix Django template variables with javascript though.
You can put a new block in your 'base.html' file, at the bottom inside the body tag like this:
{% block inline_javascript %}
{% enblock inline_javascript %}
Then inside the page you want the function to run on you put the script inside the same tags at the bottom of that page outside the 'block content' like:
{% block inline_javascript %}
<script>
const createButton = ({{ buttonCount }}) => {
containerId = "myContainerId"
container = document.getElementById(containerId)
for (var i = 0; i < {{ buttonCount }}; i++) {}
newButton = document.createElement("button")
newButton.value = "Test"
newButton.id = "testButton" + i
container.appendChild(newButton)
}
}
</script>
{% enblock inline_javascript %}

correct javasript code execution in flask

I tried to use click on button:
#app.route("/")
def test_edition_open():
return render_template("index.html")
my index.html file is:
<script type="text/javascript" src="{{ url_for('static', filename='script.js') }}"></script>
The main part is just two buttons:
<div class = "counter">
<button class = "minus">-</button>
<div class = "result">1</div>
<button class = "plus">+</button>
</div>
I tried to make My script.js file work in flask. The code is very simple, it should add numbers by clicking on button:
const plus = document.querySelectorAll('.plus');
const minus = document.querySelectorAll('.minus');
const result = document.querySelectorAll('.result');
function min()
{
return function (ev)
{
if (ev.target.nextElementSibling.innerHTML > 0)
{
return --ev.target.nextElementSibling.innerHTML;
}
}
}
function pl()
{
return function (ev)
{
return ++ev.target.previousElementSibling.innerHTML;
}
}
minus.forEach(function (dominus)
{
dominus.addEventListener('click', min());
})
plus.forEach(function (doplus)
{
doplus.addEventListener('click', pl());
})
In https://playcode.io this code worked well. How should I solve this problem?
Make sure that script file successfully connected to html file. to check this add console.log("File Connected") in your script.js file. Then open your browser console to check that console message is logged correctly. If not then try to linked your static file correctly. How to set static_url_path in Flask application
Or you can put your Javascript code in html file using script tag.
Something like this:
<script> your javascript code here</script>

Django and javascript - how to use the value of dropdown box to access the static image stored on server using the static tag

{% load static %} line 1
<html> line 2
<head> line 3
<meta charset="UTF-8"> line 4
</head>
<body>
<select id="ddlViewBy">
<option value="Pranamasana.jpg">Pranamasana</option>
</select>
<img id='cat' crossorigin="anonymous" height = "620" width = "620"/>
<button onclick = "myfun()">button</button>
<script>
function myfun() {
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
document.getElementById("cat").src = "{% static 'Pranamasana.jpg' %}"; line 16
}
</script>
</body>
</html>
Even though I have a drop down box I am hard coding the name of the image to be accessed in line 16.
I want to know the way if I can use the string 'struser' so that the image selected by user can be displayed without hard coding.
Any help would be appreciated and thanks in advance.
I am using django and this is a html page in my project
Django template executes your code before the javascript does so you can't really use the javascript concatenate string adding. So the best way is to use {% get_static_prefix %}
var staticUrl = "{% get_static_prefix %}"
var strUsr = e.options[e.selectedIndex].value;
document.getElementById("cat").src = staticUrl + strUsr

Javascript variable issue with Django

I am trying to use some javascript with my django code but have a small issue calling functions from the second js file.
I am using code from here https://github.com/mattdiamond/Recorderjs
I took the html file Matt made and removed the header and created a django template and then put the javascript files with my other static files. Those files (twitter bootstrap) all work fine.
If I open the sheet it loads fine with the record and stop buttons available. If you press them they are recorded in the log but any function that should be called in the recorderWorker.js is ignored. So I can not save the file or see it.
As far as I can tell it never calls the second javascript file. If I put alert boxes in the recorderWorker.js nothing happens but they work in the Recorder.js.
var WORKER_PATH = 'recorderWorker.js';
var Recorder = function(source, cfg){
I know it is not a problem with the code since I tested it using another Python webserver (SimpleHTTPServer) and it works great.
I have made no changes to the js files and only create this template for the html.
{% load staticfiles %}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Live input record and playback</title>
<style type='text/css'>
ul { list-style: none; }
#recordingslist audio { display: block; margin-bottom: 10px; }
</style>
</head>
And then the html file
{% extends "base_record.html" %}
{% block content %}
<h1>Recorder.js simple WAV export example</h1>
<p>Make sure you are using a recent version of Google Chrome, at the moment this only works with Google Chrome Canary.</p>
<p>Also before you enable microphone input either plug in headphones or turn the volume down if you want to avoid ear splitting feedback!</p>
<button onclick="startRecording(this);">record</button>
<button onclick="stopRecording(this);" disabled>stop</button>
<h2>Recordings</h2>
<ul id="recordingslist"></ul>
<h2>Log</h2>
<pre id="log"></pre>
<script>
function __log(e, data) {
log.innerHTML += "\n" + e + " " + (data || '');
}
var audio_context;
var recorder;
function startUserMedia(stream) {
var input = audio_context.createMediaStreamSource(stream);
__log('Media stream created.');
input.connect(audio_context.destination);
__log('Input connected to audio context destination.');
recorder = new Recorder(input);
__log('Recorder initialised.');
}
function startRecording(button) {
// alert("start recording")
recorder && recorder.record();
button.disabled = true;
button.nextElementSibling.disabled = false;
__log('Recording...');
}
function stopRecording(button) {
// alert("Stopped recording")
recorder && recorder.stop();
button.disabled = true;
button.previousElementSibling.disabled = false;
__log('Stopped recording.');
// create WAV download link using audio data blob
createDownloadLink();
recorder.clear();
}
function createDownloadLink() {
recorder && recorder.exportWAV(function(blob) {
alert("download link")
var url = URL.createObjectURL(blob);
var li = document.createElement('li');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
hf.download = new Date().toISOString() + '.wav';
hf.innerHTML = hf.download;
li.appendChild(au);
li.appendChild(hf);
recordingslist.appendChild(li);
});
}
window.onload = function init() {
try {
// webkit shim
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
window.URL = window.URL || window.webkitURL;
audio_context = new AudioContext;
__log('Audio context set up.');
__log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
} catch (e) {
alert('No web audio support in this browser!');
}
navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
__log('No live audio input: ' + e);
});
};
</script>
{% endblock %}
<body>
{% block content %}
{% endblock %}
<script type="text/javascript" src="{% static 'bootstrap/js/recorder.js' %}"></script>
</body>
</html>
Here is my settings.py
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static"
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/home/kevin/Programming/accent/static/',
)
I also faced similar issue where recorderWorker.js was not being accessed. However, the problem was solved when I did the following:
'static/filename/recorderWorker.js'
Note: Assuming that your JS file is located in the folder 'filename' which is in the static folder.
As far as Django is concerned, it looks for static files like JS files into the static folder, since you did not specify the path it did not load the file.

Categories