Skip to content
Advertisement

How to get input form without reloading from HTML to flask?

I want to retrieve the input of the fields in the form of an array to the flask, on clicking a button, and without reloading the page. All the input fields are dynamic but the input filed id is static.

image

Here, above are the input fields and I want to retrieve the input with the click of the “calculate button”.

<div class="text-light" id="input-details">
  <h4 class="card-title">Input Details</h4>

  {% for item in projectArray.typeOfInput%}

    <label for="{{item|lower}}" class="col-form-label">{{item|capitalize}}</label>
    <input type="number" class="form-control text-light bg-transparent" id="input_input" placeholder="{{projectArray.typeOfInput.get(item)}}">
    
  {%endfor%}
  <br>
  
  <div class="d-flex justify-content-center">
    <a href="#" type="submit" class="btn btn-primary">
      Calculate
    </a>
  </div>

</div>

The above code is included jinja where it is adding fields dynamically from the below dictionary.

projectArray = {
 'numOfInputs': 2, 
 'projectName': 'First-Model', 
 'typeOfInput': {'Exp': 'String/Integer', 'SALARY': 'String/Integer'}, 
}

I am trying to achieve it using js, ajax. this is what I came up with, I don’t know much of it but I tried to understand and found the below and edited it.

// form id===> execution_form

$(document).on('submit', '#execution_form', function (e) {
        console.log('Form sent to the backend');
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/execute',
            data: {
                input_fields: $("#input_input").val().serialize(),
            },
            success: function () {
                alert('Processing...');
            }
        })
    });

Advertisement

Answer

You are taking the right approach. AJAX is the only way to transfer the form without having to reload the page.

According to the specification, the “for” attribute of the label relates to the ID of the input field, so this is also dynamic. In addition, in order to serialize the data, a “name” attribute is required for each input field.

To receive the data as an array, I recommend transmitting it as JSON.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <form name="execution_form">
      {% for k,v in projectArray.typeOfInput.items() %}
      <label for="{{k|lower}}">{{k|capitalize}}</label>
      <input type="number" id="{{k|lower}}" name="{{k|lower}}" placeholder="{{v}}" />
      {% endfor %}
      <input type="submit" />
    </form>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script type="text/javascript">
    $(document).ready(function() {
      // Wait for the content to load.
      $("form[name='execution_form']").submit(function(evt) {
        // If the form is to be submitted, ignore the standard behavior.
        evt.preventDefault();
        // Serialize the inputs to an array.
        let inputFields = $(this).serializeArray();
        // Send the data as JSON via AJAX.
        $.ajax({
          method: "POST",
          url: "/execute",
          contentType: "application/json;charset=utf-8",
          dataType: "json",
          data: JSON.stringify({ input_fields: inputFields })
        }).done(data => {
          // Use the response here.
          console.log(data);
        });
      });
    });
    </script>
  </body>
</html>

The following is the route to receive the data.

@app.route('/execute', methods=['POST'])
def execute():
    print(request.json)
    return jsonify(msg='success')

I wish you success in implementing your project.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement