Flask form submission without Page Reload

Form submission is a crucial part of web applications, but traditional form submissions require page reloads, which can feel slow and disrupt user experience. Flask, combined with AJAX, allows you to submit forms asynchronously without page reloads, creating a smoother and more responsive application.

Basic Flask Setup

Let's start with a basic Flask application structure ?

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

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

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

Creating the Flask Backend

Here's the complete Flask application that handles form submission without page reload ?

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

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

@app.route('/submit', methods=['POST'])
def submit_form():
    name = request.form.get('name')
    email = request.form.get('email')
    message = request.form.get('message')
    
    # Process the data (save to database, send email, etc.)
    # For this example, we'll just return a success message
    
    return jsonify({
        'status': 'success',
        'message': f'Thank you {name}! Your message has been received.',
        'data': {
            'name': name,
            'email': email,
            'message': message
        }
    })

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

HTML Template with AJAX

Create a templates/index.html file with jQuery for handling AJAX requests ?

<!DOCTYPE html>
<html>
<head>
    <title>Flask Form Submission without Page Reload</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #0056b3; }
        .message { padding: 10px; margin: 10px 0; border-radius: 4px; }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <h1>Contact Form</h1>
    
    <div id="response-message"></div>
    
    <form id="contact-form">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>
        </div>
        
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        
        <div class="form-group">
            <label for="message">Message:</label>
            <textarea id="message" name="message" rows="4" required></textarea>
        </div>
        
        <button type="submit" id="submit-btn">Submit</button>
    </form>

    <script>
        $(document).ready(function() {
            $('#contact-form').submit(function(event) {
                event.preventDefault(); // Prevent default form submission
                
                // Disable submit button to prevent double submission
                $('#submit-btn').prop('disabled', true).text('Submitting...');
                
                $.ajax({
                    type: 'POST',
                    url: '/submit',
                    data: $(this).serialize(),
                    success: function(response) {
                        $('#response-message').html(
                            '<div class="message success">' + response.message + '</div>'
                        );
                        
                        // Clear form fields
                        $('#contact-form')[0].reset();
                    },
                    error: function() {
                        $('#response-message').html(
                            '<div class="message error">Error submitting form. Please try again.</div>'
                        );
                    },
                    complete: function() {
                        // Re-enable submit button
                        $('#submit-btn').prop('disabled', false).text('Submit');
                    }
                });
            });
        });
    </script>
</body>
</html>

How It Works

The form submission process follows these steps:

  • Event Prevention: event.preventDefault() stops the default form submission

  • AJAX Request: jQuery sends form data to the Flask backend asynchronously

  • Backend Processing: Flask processes the data and returns a JSON response

  • Dynamic Update: JavaScript updates the page with the response without reloading

  • Form Reset: The form is cleared after successful submission

Key Benefits

Traditional Form AJAX Form
Page reload required No page reload
Lost form state Preserved page state
Higher server load Reduced server load
Slower user experience Instant feedback

Error Handling

Always implement proper error handling for better user experience ?

@app.route('/submit', methods=['POST'])
def submit_form():
    try:
        name = request.form.get('name')
        email = request.form.get('email')
        message = request.form.get('message')
        
        # Validate required fields
        if not all([name, email, message]):
            return jsonify({
                'status': 'error',
                'message': 'All fields are required.'
            }), 400
        
        # Process the data here
        # Save to database, send email, etc.
        
        return jsonify({
            'status': 'success',
            'message': f'Thank you {name}! Your message has been received.'
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': 'An error occurred while processing your request.'
        }), 500

Conclusion

AJAX form submission in Flask provides a seamless user experience by eliminating page reloads. This approach improves performance, maintains page state, and allows for instant user feedback, making your web applications feel more responsive and modern.

Updated on: 2026-03-27T08:41:37+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements