Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Using Ajax to send a request. Despite using preventDefault, the page is reloading

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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');
            }
        })
    })
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!