Reputation: 43
I need to send data from my javascript front-end to my python back-end in my flask app. I cannot use input html tags. Is there any way to send information to the Flask backend without using Ajax?
Edit: Found an answer
Upvotes: 1
Views: 4066
Reputation: 43
Ok so I've found XMLHttpRequest works well. You can see an example of it being used with Flask here (base html, javascript front-end, Flask back-end). This example gets input directly from an html form but you can easily just make a new FormData object and append your own values to it.
There's also an example using fetch() to send data (use base html and back-end linked above as well).
Upvotes: 1
Reputation: 118
I encountered the very same issue recently, and this is how I did it (although you say you can't use input tags which I don't quite understand how?, sorry if this doesn't help you then). At the top of my html I created a form with an input, but gave it display none so that it stays invisible:
<form id='exampleForm' method = 'post' action='#' style='display:none'>
<input id='exInput' type='text' name='exInput'>
</form>
You have to give a name to the input to be able to access it from your Flask. Then the trick is that once you've done everything you need to do on this page, which form me was at the end of a conditional, you set the 'value' attribute of the 'exInput' text input box to what you want it to be, supposedly it has been stored in a Javascript Array previously. And then finally you submit the form.
var exInput = document.getElementById('exInput')
exInput.setAttribute('value', 'jsArrayYouHaveAlreadyDefined')
document.getElementById('exampleForm').submit()
On the Flask end, you just have to check for a POST method, and retrieve the data. (you have to import requests beforehand)
@app.route('/example/', methods = ['GET', 'POST'])
def example():
if method == 'POST':
exInput = request.form['exInput']
return render_template('example.html')
Hope this helps someone, although I am still a newbie.
Upvotes: 2