Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda