Ask Your Question
2

How can I make a call with parameter using Flask (Jinja) and jQuery?

asked 2022-08-28 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-02-08 07:00:00 +0000

pufferfish gravatar image

To make a call with parameters using Flask (Jinja) and jQuery, you can use the following steps:

Step 1: Set up your Flask route

Create a Flask route that will return the data you want to retrieve. For example:

@app.route('/data')
def get_data():
    name = request.args.get('name')
    age = request.args.get('age')
    # do something with name and age to retrieve data
    data = {'name': name, 'age': age, 'city': 'New York'}
    return jsonify(data)

In this example, the route accepts two query parameters (name and age) and returns a JSON object with the retrieved data.

Step 2: Create your HTML template

Create an HTML template that includes a form with inputs for the parameters you want to pass to the route. For example:

<form id="my-form">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br><br>
  <label for="age">Age:</label>
  <input type="text" id="age" name="age"><br><br>
  <button type="submit">Submit</button>
</form>

Step 3: Write your jQuery code

Use jQuery to handle the form submission and make an AJAX call to the Flask route. For example:

$(document).ready(function() {
  $('#my-form').submit(function(event) {
    event.preventDefault();
    var name = $('#name').val();
    var age = $('#age').val();
    $.ajax({
      method: 'GET',
      url: '/data',
      data: {
        'name': name,
        'age': age
      },
      success: function(data) {
        // do something with the retrieved data
        console.log(data);
      },
      error: function(error) {
        console.log(error);
      }
    });
  });
});

This code handles the form submission by preventing the default behavior, retrieving the values of the name and age inputs, making an AJAX call to the Flask route with the parameters as query parameters, and handling the success and error callbacks.

That's it! With these steps, you can make a call with parameters using Flask (Jinja) and jQuery.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-28 11:00:00 +0000

Seen: 12 times

Last updated: Feb 08 '23