how to seperate the script from html template when using jQuery in flask

Step 1: Create a Flask project structure with a templates folder


Step 2: Set up Flask in

from flask import Flask, render_template

app = Flask(__name__)

def index():
    return render_template('index.html')

if __name__ == '__main__':

Step 3: Create the HTML template (index.html) in the templates folder

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask jQuery Example</title>
    <script src=""></script>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
    <h1>Flask jQuery Example</h1>
    <button id="btnClick">Click me</button>
    <p id="output"></p>

Step 4: Create the jQuery script (script.js) in the static/js folder

            type: 'GET',
            url: '/api/data',
            success: function(response){

Step 5: Update the file to handle the AJAX request

from flask import jsonify

def get_data():
    # Perform any data processing here
    data = "Data from the server"
    return jsonify({'data': data})

Step 6: Run your Flask application


Visit http://localhost:5000 in your web browser and interact with the button to see the jQuery script in action. The server will respond to the AJAX request, and the response will be displayed on the webpage.