I have a select element with entries pulled from a table of names that I then want to query links based on the selected name. I want the links to display on the page once a name is selected, but I don’t know to submit the selection to flask or how to return the result of the query back to the page after it’s loaded.
I currently have an app route that sends the result of Name.query.all() as names=names but I don’t know how to take user input (say, the first name) and use it in a query and return the query [ like Link.query.filter(name_id == 1).all() ] as links=links after the page has loaded.
CodePudding user response:
You have to share you code when you ask a question, but since you're a new contributor, I'm gonna give you an answer.
you need to write some java script if you don't want to leave the page. here is an example:
<select onchange="myFunction()" id="mySelect">
...
</select>
<p id="link"></p>
<script>
myFunction() {
var value = document.getElementById("mySelect").value;
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("link").innerHTML = this.responseText;
}
xhttp.open("GET", "yourDomain/yourRoute/" value);
xhttp.send();
}
</script>
Now in flask make a route to receive that request and return the link.
@app.route("/yourRoute/<value>", methods=["GET"])
def getLink(value)
....
return link
An easier Alternative is to have the user select what they want and then submit the form. In flask, return a new template showing the link.