Ask Your Question
1

I am unable to send data from Javascript to Python using Flask and struggling with the conversion.

asked 2023-03-18 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-12-14 22:00:00 +0000

qstack gravatar image

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));
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: 2023-03-18 11:00:00 +0000

Seen: 8 times

Last updated: Dec 14 '21