Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few steps you need to take in order to send data from Javascript to Python using Flask.

  1. Create an API endpoint in your Flask app that can receive the data. This can be done using the @app.route decorator with the appropriate method (e.g. @app.route('/data', methods=['POST'])).

  2. In your Javascript code, you'll need to make an AJAX request to the API endpoint you created. You can use the fetch() function or jQuery's $.ajax() function, for example.

  3. When making the AJAX request, you'll need to include the data you want to send in the request body. This can be done using the body or data option, depending on which function you're using. You'll also need to set the Content-Type header to 'application/json' to indicate that you're sending JSON data.

  4. In your Flask endpoint, you'll need to parse the JSON data from the request body using the request.get_json() function. This will return a Python dictionary that you can use in your application.

  5. Finally, you can use the data that you've received in your Python code as needed.

Here's an example of how you might implement this in your Flask app:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/data', methods=['POST'])
def receive_data():
    data = request.get_json()
    # do something with the data
    response = {'message': 'Data received'}
    return jsonify(response)

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

And here's an example of how you might make the AJAX request in your Javascript code:

const data = {name: 'John', age: 30};
fetch('/data', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));