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

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

/project
   /static
      /js
         script.js
   /templates
      index.html
   app.py

Step 2: Set up Flask in app.py

from flask import Flask, render_template

app = Flask(__name__)

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

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

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

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

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

$(document).ready(function(){
    $("#btnClick").click(function(){
        $.ajax({
            type: 'GET',
            url: '/api/data',
            success: function(response){
                $("#output").text(response.data);
            }
        });
    });
});

Step 5: Update the app.py file to handle the AJAX request

from flask import jsonify

@app.route('/api/data')
def get_data():
    # Perform any data processing here
    data = "Data from the server"
    return jsonify({'data': data})

Step 6: Run your Flask application

python app.py

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.