I am writing a Flask App in which I want to be able to use a form to input information into a database without refreshing the page. Here is my form:
<form id="vocab_form">
<label for="name">Word:</label>
<input type="text" id="word" name="word">
<label for="def">Definition</label>
<input type="text" id="def" name="def">
<input type="submit" value="Add Term">
</form>
Here is the script I am using to send the request. It is embedded in the html file containing the form.
<script>
$(document).on('submit', '#vocab_form', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/',
data:{
word:$(#word).val(),
def:$(#def).val()
},
success:function(){
alert('success');
}
})
});
Here is the route to which I am sending the form data. It calls functions in another file to input the data into my database and to collect some information online with which to render the page.
@app.route("/", methods=["GET", "POST"])
def hello():
if request.method == "POST":
word = request.form["word"]
definition = request.form["def"]
query.add_word(word, definition)
message="Word added successfully! {} means {}".format(word, definition)
else:
message="no form data"
wordlist=query.get_all_words()
lines = web_functions.get_les_mis()
return render_template("home.html", message=message, wordlist=wordlist, lines=lines)
Although my script includes the instruction to prevent the default submit behavior for the form, the page reloads each time I submit the form. I want to prevent this. Any advice or insight would be much appreciated!
Try this instead
<script>
$(document).ready(function() {
$('#vocab_form').on('submit', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/',
data:{
word:$(#word).val(),
def:$(#def).val()
},
success:function(){
alert('success');
}
})
})
});