[python] Send data from a textbox into Flask?

I was wondering if there was a way to take something from a text box in the HTML, feed it into flask, then parse that data with Python. I was thinking this might involve some JS but I could be wrong. Any ideas?

This question is related to python flask

The answer is


Assuming you already know how to write a view in Flask that responds to a url, create one that reads the request.post data. To add the input box to this post data create a form on your page with the text box. You can then use jquery to do

var data = $('#<form-id>').serialize()

and then post to your view asynchronously using something like the below.

$.post('<your view url>', function(data) {
  $('.result').html(data);
});

All interaction between server(your flask app) and client(browser) going by request and response. When user hit button submit in your form his browser send request with this form to your server (flask app), and you can get content of the form like:

request.args.get('form_name')

Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.

from flask import request

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
    if request.method == "POST":
         #perform action here
var value = $('.textbox').val();
$.ajax({
  type: 'POST',
  url: "{{ url_for('parse_data') }}",
  data: JSON.stringify(value),
  contentType: 'application/json',
  success: function(data){
    // do something with the received data
  }
});

This worked for me.

def parse_data():
    if request.method == "POST":
        data = request.get_json()
        print(data['answers'])
        return render_template('output.html', data=data)
$.ajax({
      type: 'POST',
      url: "/parse_data",
      data: JSON.stringify({values}),
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      success: function(data){
        // do something with the received data
      }
    });