Why can I not change a html element with JS? - javascript

I'm trying to get a JS script to insert HMTL on a python flask server and it doesn't seem to want to run.
File Structure:
project
static
css
style.css
templates
demo.html
download.html
index.html
wrongLink.html
main.py
Here is the flask code that runs the webserver:
from flask import Flask, render_template, send_file
from flask import request, redirect
app = Flask(__name__)
#app.route('/')
def main():
return render_template('demo.html')
I also render some templates like this:
return render_template('download.html',
thumb=thumb, title=title, options=options, counter=counter)
I realised that I'm having trouble specifically with one piece of JS in the download.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link href="{{ url_for('static', filename='css/style.css') }}"
rel="stylesheet" type="text/css">
</head>
<body>
<div>
<form action="/getVideo" method="post">
<input type="text" name="Link" value="{{ Link }}">
<input type="submit" value="Convert">
</form>
<img src="{{ thumb }}" alt="Thumbnail" width="480" height="270">
<p>{{ title }}</P>
<p id="demo"></p>
<form id="options">
<input type="submit" value="Download">
</form>
</div>
<script type="text/javascript">
window.alert("JS works");
var i;
var options = JSON.parse{{options | tojson}};
for (i = 0; i < options.length; i++) {
out += '<input type="radio" value="' + options[i]["res"] += '"><br>';
}
document.getElementById("demo").innerHTML = "hi";
</script>
</body>
</html>
Neither the alert window or the element edit execute so I'm not sure what's happening there.

Related

Add href in OnClick attribute in html form

I want to redirect to the python flask route home after showing the alert window.
<input type="submit" value="Register" onclick="call(); log();"></input>
Here are both functions.
<script>
function call()
{
window.alert("Congragulations! You Registerd Sucessfully ");
}
</script>
<script>
function log()
{
<a href="/home" > </a>
}
</script>
If I understood your project correctly, you want to forward the user after he has registered. At the same time, a message should appear that the process was successfully completed.
I think your javascript approach is not sufficient for this, since the data must first be sent from the client to the server so that the process is complete. Here the inputs should also be validated and will likely be processed or stored in some way.
I have written a small example for you, which accepts form data and checks it. If the verification is successful, the user is redirected and a message appears. To forward and display the message I use redirect and flash from the flask package.
Python Flask
import re
from flask import Flask
from flask import (
flash,
redirect,
render_template,
request,
session,
url_for
)
app = Flask(__name__)
app.secret_key = b'your secret here'
#app.route('/')
def home():
return render_template('index.html')
#app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
if username and re.match(r'^[a-z0-9\_\-]+$', username, re.IGNORECASE):
session['username'] = username
flash('Congragulations! You Registerd Sucessfully.')
return redirect(url_for('home'))
return render_template('register.html')
HTML (index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<nav>
<ul style="list-style: none;">
<li>Register</li>
</ul>
</nav>
{% with messages = get_flashed_messages() -%}
{% if messages -%}
<ul class="flashes">
{% for message in messages -%}
<li>{{ message }}</li>
{% endfor -%}
</ul>
{% endif -%}
{% endwith -%}
<h1>Welcome {{ session.get('username', 'Guest') }}!</h1>
</body>
</html>
HTML (register.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<form method="post">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</div>
<input type="submit" value="Register" />
</form>
</body>
</html>

Display python result in html using JavaScript | python eel

I want to send result to JavaScript to display the result in html using eel.
I'm adding the two numbers reading it from JavaScript through html & I want to display the result in html side at the end..
main.py
import eel
import requests
eel.init('web')
#eel.expose
def sum(a,b):
c = int(a) + int(b)
print(c)
return c
eel.start('index.html', size=(500, 500))
main.js
function sum() {
var a = document.getElementById("data_1").value;
var b = document.getElementById("data_2").value;
eel.sum(a, b);
}
index.html
<!doctype html>
<html lang="en">
<head>
<title>Test eel</title>
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript" src="/myscript.js"></script>
</head>
<body>
<h3 class='label_'>Num 1 </h3>
<input type="text" id="data_1" >
</br>
<h3 class='label_'>Num 2 </h3>
<input type="text" id="data_2" >
</br>
<input type="button" class="submit" value="submit" onclick="sum()"></br>
output
<div id='file-name'>---</div>
</div>
</body>
</html>
You can use JavaScript callback function to pass the return value to html
main.js
function sum() {
var a = document.getElementById("data_1").value;
var b = document.getElementById("data_2").value;
eel.sum(a, b)(callback); // change here
}
// add function as
function callback(c) {
document.getElementById("data").value = c;
}
In index.html add this below code to print result on html side
index.html
<div>
Result : <input type="text" id="data" >
</div>

My list is coming out undefined for all values when parsing with JSON? Why?

New to this. So im printing a list. Im getting names from a button. All the names are coming out as undefined? It's something im doing with localstorage im sure. Idk what tho.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function passVal() {
newList = [];
var newName = document.getElementById("addname").value;
addedNamesList = newList.push(newName);
localStorage.setItem("newList1", JSON.stringify(addedNamesList));
var LL = JSON.parse(localStorage.getItem("newList1"));
document.getElementById("nameList").innerHTML += "<li>" + LL[LL.length-1] + "</li>";
}
</script>
<ul id="nameList"></ul>
{% extends "navigation.html" %}
{% block content %}
<p> Add a name: </p>
<meta charset="UTF-8">
<form action="home.html">
<input type='text' input name='name' id='addname'>
<input type="button" id="add" value="Submit" onclick="passVal()">
</form>
{% endblock %}
<title> Add Name Page </title>
</head>
<body>
</body>
</html>
JSON.stringify(addedNamesList) should be JSON.stringify(newList). The push() method doesn't return a new list, it modifies the list in place and returns the length of the list. So you're storing 1 in local storage, not the list.

Django, calendar widget doesn't work with ModelForm and Form Media

I found one blog. It explains how apply calendar widget with form media. It is what I exactly want to make. so I followed instructions.
But js and css files doesn't work in widget. I tried to figure out this problem. I spent quite much time by searching and reading stuffs. But I can't get what's wrong in my situation exactly. Well, It could be very easy question but I will appreciate if you can give me any hint to figure out this!
model.py
class Birthday(models.Model):
birthday = models.DateField(null=True)
views.py
def register_birthday(request):
if request.method == 'POST':
form = BirthdayForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success')
else:
form = BirthdayForm()
return render(request, 'sale/registerbirthday.html', {'form':form})
forms.py
class DateUIWidget(forms.TextInput):
def _media(self):
return forms.Media(css = {
"all": ("tiny-date-picker.css",)
},
js = ("tiny-date-picker.js", "date-init.js",))
media = property(_media)
class BirthdayForm(forms.ModelForm):
class Meta:
model = Birthday
fields = ('birthday',)
widgets = {
"birthday" : DateUIWidget(attrs={'class':'dateuiwidget', 'id':'id_birthday'}),
}
actually I wrote at first like below. but I changed to check if it works when I use media as a dynamic property.
class DateUIWidget(forms.TextInput):
class Media:
css = {
"all": ("tiny-date-picker.css",)
}
js = ("tiny-date-picker.js", "date-init.js",)
forms.py first
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{{ form.medai}}
I changed it because I read that I should read this when I changed.
As we have already seen, the string representation of a Media object is the HTML required to include the relevant files in the <head> block of your HTML page.
<html>
<head>
{{ form.media }}
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
under myapp/static/date-init.js
$(".dateuiwidget").each(function(){
return TinyDatePicker(this);
});
I copied two files(tiny-date-picker.js,tiny-date-picker.css) under myapp/static/.
I got two files from here
it shows widget in a form without error. I assume that somehow js, css file didn't apply to this widget.
html source code
<html>
<head>
<link href="/static/tiny-date-picker.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/static/tiny-date-picker.js"></script>
<script type="text/javascript" src="/static/date-init.js"></script>
</head>
<body>
<form action="." method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='VC8ahwDLBOsy4IlAzf1iIiukK7ZvTcGDQjL9RxywlauCOX3c8rG7DVJ1ClozHEEW' />
<p><label for="id_birthday">Birthday:</label> <input class="dateuiwidget" id="id_birthday" name="birthday" type="text" required /></p>
<input type="submit">
</form>
</body>
</html>

Embedding a bokeh plot in Flask

I am expecting to get a simple line bokeh plot returned by Flask, but what I get when I browse to localhost:5002/simpleline is this:
('', '
')
I have two files. The Python file:
from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/simpleline/')
def simpleLine():
fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
div=components(fig)
return render_template('simpleline.html',div=div)
show(fig)
if __name__ == "__main__":
app.run(debug=True,port=5002)
And the HTML template:
<!doctype html>
<html>
<head>
<title>Figure examples</title>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh-0.7.1.min.css" type="text/css" />
<script type="text/javascript"src="http://cdn.bokeh.org/bokeh-0.7.1.min.js"></script>
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>
I am sure I am missing something essential here.
After mn's answer, it was found out that components() produces two elements, a Javascript string, and an html div. So, I updated my scripts as follows, but this time the web page shows as blank.
from bokeh.plotting import figure, show, output_file
from bokeh.embed import components
from flask import Flask, render_template
app=Flask(__name__)
#app.route('/simpleline/')
def simpleLine():
fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
global script
global div
script,div=components(fig)
return render_template('simpleline.html',div=div,script=script)
output_file("simpleline.html")
show(fig)
fig=figure(title="Sensor data")
fig.line([1,2,3,4],[2,4,6,8])
script,div=components(fig)
if __name__ == "__main__":
app.run(debug=True,port=5002)
And the HTML template:
<!doctype html>
<html>
<head>
<title>Figure examples</title>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh-0.9.0.min.css" type="text/css" />
<script type="text/javascript" src="http://cdn.bokeh.org/bokeh-0.9.0.min.js"></script>
{{ script|safe }}
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>
I tried all bokeh-0.7.1.min.js, 0.9, and 0.10, but I still got the same blank page.
components() returns (script, div) tuple with <script> that contains the data for your plot and an accompanying <div> tag that the plot view is loaded into:
http://docs.bokeh.org/en/latest/docs/user_guide/embed.html#components
script, div = components(fig)
return render_template('simpleline.html',div=div, script=script)
template
<!doctype html>
<html>
<head>
<title>Figure examples</title>
<link rel="stylesheet" href="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.css" type="text/css" />
<script type="text/javascript" src="http://cdn.bokeh.org/bokeh/release/bokeh-0.10.0.min.js"></script>
{{ script|safe }}
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>
Alternatively, you can also use autoload_static instead of components if you want the bokeh js and css to load automatically. Also you can save the js into a filepath and use only the div in the html to access it.
Here is a sample code that I worked with:
from bokeh.embed import autoload_static
from bokeh.resources import CDN
.............
.............
js, div = autoload_static(bar, CDN, '/static/bokeh/plot.js')
with open('static/bokeh/plot.js', 'w') as f:
f.write(js)
And then in the html file include only the div tag (includes the path of the js script).
<!doctype html>
<html>
<head>
<title>Figure examples</title>
</head>
<body>
<div class='bokeh'>
{{ div|safe }}
</div>
</body>
</html>

Categories

Resources