Calaf Calaf - 28 days ago 18
Javascript Question

Update a field without (re)loading a Flask page

The following (nonworking) Flask app

index.html

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input type="button"
onclick="location.href='/increaseNumber/<num>';" />
<em>{{ num }}</em>
<script>
var num = 0;
</script>
</body>


app.py

import os
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html', num=0)

@app.route('/increaseNumber/<num>', methods=['POST'])
def increment(num):
return render_template('index.html',
num=int(num)+1)

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


attempts to do the following. A number is displayed. Everytime the button is clicked, the number is incremented on the server, and the new number is sent back to
index.html
.

Crucially, the button press doesn't load another page. The same page remains. Only the number is updated. How do I do this?

Answer

Send a ajax request onclick of the button element. I am including jQuery in the heading so you can select elements with css selectors by wrapping them around $ like $('#inc-num') selects element with id named inc-num and send ajax requests with $.ajax

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
    <input type="button" id="inc-num" value="Increment Number"/>
    <em id="number">{{ num }}</em>
    <script>
        $('#inc-num').click(function(){
            var num = parseInt($('#number').text()),
                incNum = num + 1;
            $.ajax( "/increaseNumber/" + num + 1)
             .done(function() {
                $("#number").text(incNum);
             })
             .fail(function() {
                alert( "error" );
             });
        });
    </script>
</body>

You can look up the jQuery ajax docs for more info on how to use $.ajax