jQuery AJAX Forms Submit with Python Flask
Submitting forms without refreshing is a common feature of many websites.
from flask import Flask, render_template, url_for, request, jsonify app = Flask(__name__) @app.route('/') def index(): return render_template('form.html') @app.route('/process', methods=['POST']) def process(): email = request.form['email'] name = request.form['name'] if name and email: newName = name return jsonify({'name' : newName}) return jsonify({'error' : 'Missing data!'}) if __name__ == '__main__': app.run(debug=True)
//templates\form.html <!DOCTYPE html> <html> <head> <title>AJAX Example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="{{ url_for('static', filename='js/form.js') }}"></script> </head> <body> <div class="container"> <br><br><br><br> <form class="form-inline"> <div class="form-group"> <label class="sr-only" for="emailInput">Email address</label> <input type="email" class="form-control" id="emailInput" placeholder="Email"> </div> <div class="form-group"> <label class="sr-only" for="nameInput">Name</label> <input type="text" class="form-control" id="nameInput" placeholder="First Name"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> <br> <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div> <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div> </div> </body> </html>
//static\js\form.js $(document).ready(function() { $('form').on('submit', function(event) { $.ajax({ data : { name : $('#nameInput').val(), email : $('#emailInput').val() }, type : 'POST', url : '/process' }) .done(function(data) { if (data.error) { $('#errorAlert').text(data.error).show(); $('#successAlert').hide(); } else { $('#successAlert').text(data.name).show(); $('#errorAlert').hide(); } }); event.preventDefault(); }); });