Code dynamic dropdown using Python, sqlite3, HTML and JavaScript - javascript

I want to fetch userdata from sqlite DB table and list them as a dropdown list in my HTML code. I am new to Python. I tried writing a code, but it failed. list_fetched is my users list that I fetched from db table.
#app.route('/trail', methods=['POST', 'GET'])
def index():
list_tested = db_dropdown()
return render_template("try.html", trail1=list_fetchted)
return "hi"
try.html:
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trail1|tojson }};
function clicked()
{
alert("trail1[0]")
}
</script>
</body>
</html>
No value is getting displayed.

I would recommend looking at the quick start guide for Flask, it may give some advice on your problem and help with your future learning.
(https://flask.palletsprojects.com/en/1.0.x/quickstart/)
I have a solution for your issue (I have removed any sqlite access but sure you can put that in):
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("try.html", trial1=['1', '2'])
Then your try.html file needs to be placed in /templates/try.html in your project directory. By default this is where Flask references templates.
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trial1|tojson }};
function clicked()
{
alert(trail1[0])
}
</script>
</body>
</html>
Enjoy learning python :)

Related

Python flask script not executing as expected

I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.
I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.
python code:
from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve
app = Flask(__name__)
#rendering the HTML page which has the button
#app.route('/json')
def json():
return render_template('json.html')
#background process happening without any refreshing
#app.route('/background_process_test')
def background_process_test():
print ("Hello")
return ("nothing")
if __name__ == "__main__":
app.debug = True
serve(app, host='0.0.0.0', port=8080) #WAITRESS!
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
<script src="{{url_for('static', filename='jquery-3.6.0.min.js')}}"></script>
<script type=text/javascript>
(function() {
('a#test').on('click', function(e) {
e.preventDefault()
$.getJSON('/background_process_test', function(data) {
//do nothing
})
return false;
})
})
</script>
</head>
<body>
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
</body>
</html>
Update:
Network tab
i somehow deleted the '$' sign. It was giving an error due to spacing in visual studio. Setting the spacing right, solved the issue. Many thanks for pointing me in the right direction.
There is a typo in the following code:
('a#test').on('click', function(e) {
...
})
Specifically, your attempt to use jquery get the list of elements that match 'a#test'. The code should be:
$('a#test').on('click', function(e) {
...
})

How can I get a User input and add it in a url and open the url in a new tab?

I know nothing about it.
I need to make a simple website.
I will take an input from user.
Suppose the input is 'LOL'
Then I need to open a new tab with this url - "https://www.help.me/LOL"
#Help me Please
You can do it by using django forms
In your project directory in views.py file you can use this code
from django import forms
from django.http import HttpResponseRedirect
class inputform(forms.Form):
inputfield = forms.CharField(label="Input")
def index(request):
if request.method == "POST":
x = inputform(request.POST)
if x.is_valid():
y = x.cleaned_data["inputfield"]
return
HttpResponseRedirect(f"https://www.help.me/{y}")
return render(request, "index.html", { "form":
inputform() }
In HTML, you can write the following code to represent the Input Field in HTML page
in index.html;
<!DOCTYPE html>
<html lang="en">
<head>
<title> xyz </title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
</body>
</html>
By this you will get your desired results

How to output $.get() method JQuery with Flask

I could not output the data created in Flask to JQuery in a Html page.
I am testing $.get() method in JQuery with Flask. The task is to return a String to a Html page and display it as paragraph. But the result cannot be displayed. Can someone shed a light on this issue. Thanks!
Here is the code in Flask
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/', methods=["GET"])
#app.route('/hello', methods=["GET"])
def hello():
return jsonify('<h1>Hello Flask !!!</h1>')
Here is the html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Events </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function()
{
$("#btnGet").click(function()
{
//$.get('https://httpbin.org/get',
$.get('http://localhost:5000/hello',
function(data)
{
$("#getInfo").text(data)
});
});
});
</script>
</head>
<body>
<button id="btnGet">Click to Get Info </button>
<p id="getInfo"></p>
</body>
</html>
As new to web programming, after hours trial and error, finally found out that I am not placing the html under static folder and run it in Eclipse Environment. After open it up in http://localhost:5000/static/test.html then it works as expected.

How to access external javascript files through jinja[Flask]?

I wanna know whether i can access external javascript files through jinja?
It's working well with html files or with js embedded in html files but not when javascript file is external.
code:
#app.route('/')
def default():
return render_template('main.html', var1 = 1, var2 = 2)
main.html code:
<html>
<body>
<p>The first value is {{var1}}</p>
<script src="main.js"></script>
</body>
</html>
main.js file:
window.onload=function(){
console.log('{{var2}}');
};
now the jinja code in main.js is not working
Maybe it's not possible to use it in external js?
If someone can help, please reply to this thread.
You need to understand how Jinja works. When you run the commmand
return render_template('main.html', var1 = 1, var2 = 2), it gets processed in the following way:
The Flask server opens the main.html template
Renders/replaces all the defined Jinja variables i.e. the context into the template
Sends the rendered HTML to the client.
Hence the variables are not loaded into the {{ var }} place-holders on the client side but at the server side.
Therefore to achieve what you are trying to do you could do something as follows:
In main.html code:
<html>
<body>
<p>The first value is {{var1}}</p>
<script>var var2 = {{var2}};
<script src="main.js"></script>
</body>
</html>
In main.js code:
window.onload=function(){
console.log(var2);
};
Note: We have added the script inside HTML code before calling main.js which the dependent script.
Let me know if this solves your issue and you have understood the explanation.
TLDR; Pass your flask variable to a global JS variable from your HTML file.
I don't think that it's possible to access external JavaScript files directly from Flask. But you can use this hack, it works with many templating languages (Jinja, EJS...)
main.py:
#app.route('/')
def default():
return render_template('main.html', var1 = 1, var2 = 2)
main.html
<html>
<body>
<p>The first value is {{var1}}</p>
<!-- Insert this <script/> tag before loading you main.js -->
<script type="text/javascript"> window.myVar1 = "{{var1}}" </script>
<script src="main.js"></script>
</body>
</html>
main.js
window.onload=function(){
// Now you can access to myVar1 directly
console.log(myVar1);
};

Datalist from python list

I am trying to generate a datalist on my website that comes from a list on python.
My html file is like this:
<!DOCTYPE html>
<html>
<body>
<form>
<input list="hschools" name="hschool">
<datalist id="hschools">
{% for elem in hsch %}
<option value= {{elem}}>
{% endfor %}
</datalist>
<input type="submit">
</form>
</body>
</html>
And is saved in trying.html
My main.py file is:
from flask import Flask,render_template
app=Flask(__name__)
#app.route("/")
def index():
hsch=["a","b","c"]
return render_template("trying.html")
if __name__=="main":
app.run()
I then try to run the web-app and I do not get anything. Can you see my error?
Maybe I am not running it correctly... Thanks!
render_template needs hsch to be passed:
return render_template("trying.html", hsch=hsch)

Categories

Resources