1

I am trying to submit form data to flask using jquery ajax request and then adding the returned html to the current page. I've tried tweaking according to similar answers on other threads, but nothing works. I'm not getting errors in the console, just no response.

html with script:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <title></title>
</head>
<body>
<h1>Add Numbers!</h1>
<div id="bread">
    <form action="" id="numberAdd" role="form">
        <div id="content">
            <div id="bob">
                <label>Bob Has:</label>
                <input type="text" id="bobNum" name="bob">
            </div>
            <div id="sam">
                <label>Sam Has:</label>
                <input type="text" id="samNum" name="sam">
            </div>
            <button type="submit" id="num-butt">Submit</button>
        </div>
    </form>
</div>
<script>
$(document).ready( function() {
        $(":button").click(function(){
    $.post('/addNumber', $('form').serialize(), function(response){
        $('#reply').empty().append(response);
        });
    });
  });

</script>
<div id="reply">
</div>
</body>
</html>

Flask:

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def homepg():
    return render_template('index.html')

@app.route('/addNumber', methods=["GET", "POST"])
def addNums():
    x = int(request.form['bob'])
    y = int(request.form['sam'])
    z = x + y
    return render_template('test.html',z=z)

if __name__ == "__main__":
    app.debug = True
    app.run()

1 Answer 1

1

The reason you're not seeing the ajax request when clicking the Submit button is because at the same time the ajax call is made, the browser is submitting the form back to the server and then loading the results.

You can prevent that from happening a few different ways, but the simplest in your example is changing the button type to "button" instead of "submit"

<button type="button" id="num-butt">Submit</button>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Works perfectly now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.