Using Flask to Handle Form Data with AJAX Requests

Posted by

JavaScript with Flask using POST

JavaScript with Flask using POST

Flask is a web framework for Python that allows you to easily create web applications with a minimal amount of code. By combining Flask with JavaScript, you can create dynamic and interactive web applications. In this article, we will explore how to use JavaScript with Flask using the POST method.

Setting up Flask

First, you will need to install Flask by running the following command in your terminal:

pip install Flask

Once you have Flask installed, you can create a new Flask app by creating a new Python file called app.py and adding the following code:


from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
data = request.get_json()
return jsonify({'message': 'Received data: ' + data['name']})

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

Creating the JavaScript code

Next, create a new HTML file called index.html and add the following JavaScript code to make a POST request to your Flask app:

const data = {name: 'John Doe'};

fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data));

Running the Flask app

To run your Flask app, simply execute the following command in your terminal:

python app.py

Your Flask app should now be running on http://127.0.0.1:5000/. If you open your index.html file in a web browser, you should see the message ‘Received data: John Doe’ printed in the console.