skip to Main Content

I’m trying to pass two async values from html to flask with ajax. I created a simple html with two buttons and two inputs. I want to pass each variable with a separate button click.
I am getting the following message:error message

HTML:

<form action="/" method="POST">
  <input type="number" id="val1" name="val1" value="1">
  <button type="submit" value="value1" name="btn1">Click1</button><br>
  <input type="number" id="val2" name="val2" value="2">
  <button type="submit" value="value2" name="btn2">Click2</button><br>
</form>

JS:

value1 = document.getElementById("val1").value;
value2 = document.getElementById("val2").value;

$.ajax({
        type: 'POST',
        url: "/",
        data: JSON.stringify[(value1, value2)],
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function(data){}
});

PY:

@app.route('/', methods=['GET', 'POST'])
def start():
    if request.method == 'POST':
        if request.form['submit'] == 'value1':
            data = request.get_json()
            value1 = data['value1']
            print(value1)
        elif request.form['submit'] == 'value2':
            data = request.get_json()
            value2 = data['value2']
            print(value2)
    return render_template('index.html')

Could someone please take a look at this and write me why this is happening, and how can I solve it?

EDIT:
I changed my .py and .js files, and I’m seeing some progress, but I still can’t pass the value to flask…

HTML:

<form action="/" method="POST">
  <input type="number" id="val1" value="25" min="25" max="35">
  <button type="submit" value="value1" name="btn">Click1</button><br>
  <input type="number" id="val2" name="val2" value="15" min="15" max="35">
  <button type="submit" value="value2" name="btn">Click2</button><br>
</form

When I click any button, it wants to print data, but I always get None in the response

PY:

@app.route('/', methods=['GET', 'POST'])
def start():
    if request.method == 'POST':
        if request.form.get('btn') == 'value1':
            data = request.get_json()
            print(data)
        elif request.form.get('btn') == 'value2':
            data = request.get_json()
            print(data)
    return render_template('index.html')

JS:

var value1 = document.getElementById('val1').value;
var value2 = document.getElementById('val2').value;
$.ajax({
  type: 'POST',
  url: '/',
  data: JSON.stringify({"A":value1}, {"B":value2}),
  contentType: "application/json;charset=utf-8",
  success: function(data){}
});

In my opinion, the problem is here part od code in .py:

data = request.get_json()
print(data)

When I changed this to print(data['A']) then I get a lot of errors

or here in .js:

data: JSON.stringify({"A":value1}, {"B":value2}),

Could someone please help me?

2

Answers


  1. It looks like you mistyped this line:

    data: JSON.stringify[(value1, value2)],
    

    try replacing it with:

    data: JSON.stringify({value1, value2}),
    
    Login or Signup to reply.
  2. If you define two buttons with the type "submit" in the same form
    do they behave the same. The entire form is transmitted for both.
    It is easier for you to split the form if you want to transfer each value in a
    separate request.

    <form name="form-1">
      <input type="number" name="number-1" value="1" />
      <button type="submit">Click Me</button>
    </form>
    
    <form name="form-2">
      <input type="number" name="number-2" value="2" />
      <button type="submit">Click Me</button>
    </form>
    

    Within a transmission, the data is formatted in a predefined format.
    If you submit the data as a form, you use the type "application/x-www-form-urlencoded"
    or "multipart/formdata". For JSON it is "application/json".

    $(document).ready(function() {
      // when the document has finished loading
      ["form[name='form-1']", "form[name='form-2']"].forEach(sel => {
        // ask for a form based on his name and add an event listener for a submit event
        $(sel).submit(function(event) {
          // ignore the default behavior
          event.preventDefault();
    
          // send as form (application/x-www-form-urlencoded)
          $.post("/", $(this).serialize())
            .done((data, textStatus, jqXHR) => {
                console.log(data);
            })
            .fail((jqXHR, textStatus, errorThrown) => {
              console.error(errorThrown);
            });
    
    
          // send as json (application/json)
          let data = {};
          $(this).serializeArray().forEach(elem => {
            data[elem['name']] = parseInt(elem['value']);
          });
          $.ajax({
            type: "POST",
            url: "/",
            data: JSON.stringify(data),
            contentType: "application/json",
            dataType: "json",
            success: function(data, textStatus, jqXHR) {
              console.log(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.error(errorThrown);
            }
          });
    
        });
      });
    });
    

    Depending on the transmission format used, the data within your route can be
    queried in different ways. In the case of a transmission as
    "application/x-www-form-urlencoded" or "multipart/form-data"
    they are within "request.form", with "application/json" they are within
    "request.json".

    The assignment of the values is based on the name of the respective input field.
    Buttons are not sent.

    The error message appeared because you asked for a value within a dictionary,
    which was not there. When asked with get, the error that is thrown by the missing key is bypassed and in this case None is returned.

    from flask import jsonify 
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            
            if request.is_json:
                data_type = 'json'
                data = request.get_json()
                print('json-data:', data)
            else:
                data_type = 'form'
                keys = ('number-1', 'number-2')
                data = { k:request.form[k] for k in keys if k in request.form }
                print('form-data:', data)
            
            # answer as json
            return jsonify(result=data, type=data_type)
        
        return render_template('index.html')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search