There are a few steps you need to take in order to send data from Javascript to Python using Flask.
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'])
).
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.
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.
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.
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));
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
Asked: 2023-03-18 11:00:00 +0000
Seen: 8 times
Last updated: Dec 14 '21
How can a list be sorted alphabetically within a console application?
What is a more effective method for substituting a value in the query string of a specific URL?
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?