Issue
I have a dropdown select2 field with 3 different values. But how can i send the selected value from the dropdown to a variable in my flask program? Here´s my following code and what i tried so far
<script type="text/javascript">
//var hugo=document.getElementById("fmea").value;
$(document).on('submit','#form',function(e)
{
e.preventDefault();
$.ajax({
type:'POST',
url:'/index',
data:{
event:$("#event").val(),
context:$("#context").val(),
//'fmea[]':$("#fmea.select2").val()
//fmea:$('.test').select2(content[0])
fmea:JSON.stringify(fmea)
},
//traditional:true,
success:function()
{
draw();
}
})
});
</script>
select2
<script>
var content = [
{id: 0, text: "Event1"},
{id: 1, text: "Event2 "},
{id: 2, text: "Event4"},
];
$(".test").select2({
data:content,
// minimumInputLength: 2,
width: '35%',
multiple:true,
placeholder:"Enter another event",
// templateResult:formatState
});
and the html code
<form method="post" id="form" enctype="multipart/form-data">
<input type="text" name="event" id="event" class="btn" placeholder="Event" >
<input type="text" name="context" id="context" class="btn" placeholder="Context" >
<input type ="text" name="fmea" id="fmea" class="btn test" placeholder="Select another Event">
<br>
<br>
<button type="submit" class="btn btn-primary" onclick="hide()" >Show Graph</button>
</form>
and python
fmea=request.form.get("fmea")
I´m getting the first two input values easily, but the fmea tag returns None. If you could give me a hint how to get the selected value, I´d appreciate it very much.
Edit Via a db connection, i´m getting data which i store in a python list. This list i want to pass to select2 so the user can select the value.
app.py
@application.route("/autocomplete",methods=["POST","GET"])
def autocomplete():
#getting topic names
q1="MATCH (n:Topic) RETURN n"
nodes=neo4j_session.run(q1)
node_result = nodes.data()
node_raw=list()
for d in node_result:
for key in d:
node_raw.append(d[key])
nodes=list()
for i in node_raw:
nodes.append(i['Name'])
return jsonify(nodes)
@application.route('/index', methods=["POST","GET"])
def index():
if request.method == "POST":
df=pd.DataFrame()
topic=request.form.getlist("topic")
topic=''.join(str(x) for x in topic)
print(topic)
query=get_final_query(topic)
results=neo4j_session.run(query).data()
df=pd.DataFrame.from_dict(results)
#df=df.drop_duplicates()
df=df.reset_index(drop=True)
return render_template("dashboard.html",query=query,tables=[df.to_html(classes="table table-striped table-hover table-sm",header=True)])
return render_template("dash.html")
select2 right now
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(contentUri, dataUri) {
$(document).ready(function() {
$('select[name="topic"]').select2({
ajax: {
url: "/index",
dataType: 'json'
},
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="myform"]').bind(function(evt) {
//evt.preventDefault();
$.ajax({
method: 'POST',
url: dataUri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.autocomplete') | tojson }});
Solution
The example below shows you how to submit a form with a select box like yours to the server using AJAX.
As soon as a submit event is fired, the entire form is formatted accordingly via the serialize
function and then sent.
Since you have chosen a variant of the selection field in which several options can be selected, the ImmutableMultiDict
provided by the request.form
object contains a list of tuples. In this case you can use request.form.getlist(...)
to query the values contained using the name of the selection box, as you already know from other input fields. The return value corresponds to a list with the selected values. These are automatically converted by specifying the type parameter.
Flask (app.py)
from flask import Flask
from flask import (
render_template,
request,
jsonify
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/data', methods=['POST'])
def data():
events = request.form.getlist('events', type=int)
return jsonify(selected=events)
HTML (templates/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Select2 Example</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<form name="my-form" method="post">
<select name="events"></select>
<button type="submit">Submit</button>
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(uri) {
$(document).ready(function() {
const content = [
{id: 0, text: 'Event 1'},
{id: 1, text: 'Event 2'},
{id: 2, text: 'Event 3'},
];
$('select[name="events"]').select2({
data: content,
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
$.ajax({
method: 'POST',
url: uri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.data') | tojson }});
</script>
</body>
</html>
If you want to pass the selectbox entries through from python, you can pass them to the template. Within your JavaScript code you then use the jinja filter tojson
to convert the list into a JavaScript array.
from flask import Flask
from flask import (
render_template,
request,
jsonify
)
app = Flask(__name__)
@app.route('/')
def index():
items = [
{ 'id': 0, 'text': 'Event 1' },
{ 'id': 1, 'text': 'Event 2' },
{ 'id': 2, 'text': 'Event 3' },
]
return render_template('index.html', **locals())
@app.route('/data', methods=['POST'])
def data():
events = request.form.getlist('events', type=int)
return jsonify(selected=events)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Select2 Example</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<form name="my-form" method="post">
<select name="events"></select>
<button type="submit">Submit</button>
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(uri, content) {
$(document).ready(function() {
$('select[name="events"]').select2({
data: content,
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
$.ajax({
method: 'POST',
url: uri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.data') | tojson }}, {{ items | tojson }});
</script>
</body>
</html>
As an alternative, you can also get the list via AJAX.
from flask import Flask
from flask import (
render_template,
request,
jsonify
)
app = Flask(__name__)
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/content')
def content():
q = request.args.get('q', '')
items = [
{ 'id': 0, 'text': 'Event 1'},
{ 'id': 1, 'text': 'Event 2'},
{ 'id': 2, 'text': 'Event 3'},
]
results = [item for item in items if q in item['text']]
return jsonify(results=results)
@app.route('/data', methods=['POST'])
def data():
events = request.form.getlist('events', type=int)
return jsonify(selected=events)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Select2 Example</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<form name="my-form" method="post">
<select name="events"></select>
<button type="submit">Submit</button>
</form>
<output name="result"></output>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
(function(contentUri, dataUri) {
$(document).ready(function() {
$('select[name="events"]').select2({
ajax: {
url: contentUri,
dataType: 'json'
},
width: '35%',
multiple: true,
placeholder: 'Enter another event'
});
$('form[name="my-form"]').submit(function(evt) {
evt.preventDefault();
$.ajax({
method: 'POST',
url: dataUri,
data: $(this).serialize()
}).done(function(data) {
$('output[name="result"]').html(data.selected.join(','));
})
});
});
})({{ url_for('.content') | tojson }}, {{ url_for('.data') | tojson }});
</script>
</body>
</html>
Answered By - Detlef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.