Home > Back-end >  Get data from Flask on Submit to Browser as Input for Bootstrap Modal
Get data from Flask on Submit to Browser as Input for Bootstrap Modal

Time:05-20

I have a button that submits a user input form:

<input  type="submit" name="submit_button" value="View Code" id="retrieve">

After the submit I have Flask functions that process the data and returns it:

@app.route("/", methods=["GET", "POST"])
@app.route("/home")
def filters():
  if request.method == "POST":

      # Get all input params
      <assigning variables based on request.form[key]>

      # button functionality
      submit_button = request.form["submit_button"]
      if submit_button == "View Data":
          df = <function to get data as pd.DataFrame based on request.form[keys]>
      
          return render_template(
              "view.html", 
              column_names=df.columns.values,
              # data=df.to_html()
              row_data=list(df.values.tolist()),
              zip=zip,
          )

      elif submit_button == "View Code":
          sql_code = <function to process request>
          return jsonify({'sql_code': sql_code})

  return render_template(
          "home.html",
          show_titles=show_titles,
          station_names=station_names,
      )

What I'm having trouble figuring out is the jQuery AJAX call to get this data back to client. What am I doing wrong here?

$("#retrieve").click(function(e) {
  e.preventDefault();

  var sql_code = $("#sql_code").val();

  $.ajax({
    url: "/", //home page route name
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({sql_code: sql_code}),
    success: function(data) {
      alert(JSON.stringify(data))
    },
    error: function(xhr) {
      alert('something went wrong'   xhr);
    }
  })
});

CodePudding user response:

Your server is not expecting JSON data(it's expecting form-data) so don't send JSON data, send form data.

$("#retrieve").click(function(e) {
  e.preventDefault();

  var sql_code = $("#sql_code").val();

  $.ajax({
    url: "/", //home page route name
    type: "POST",
    dataType: "json",
    data: {sql_code: sql_code, [this.name]: this.value},// the second value is for the button that was pressed
    success: function(data) {
      console.log(data);
    },
    error: function(xhr) {
      alert('something went wrong'   xhr);
    }
  })
});

CodePudding user response:

For anyone trying to send data back from Flask to the browser (client) for Modals via single input button (along with other buttons), here is my solution:

routes.py:

if request.method == "POST":
    if len(request.form) > 0: # if submitting POST via input
        submit_button = request.form[<key>]
        ... 
    elif len(request.form) == 0: # if submitting POST via AJAX
        submit_button = request.json[<key>]
        ...
    
    if submit_button == "<value tag of HTML button>":
       obj = <APPLY FUNCTIONS>
       return jsonify(obj)

home.html:

<script>
$( function() {
    function convertFormToJSON(form) {
        const array = $(form).serializeArray(); // Encodes the set of form elements as an array of names and values.
        const json = {};
        $.each(array, function () {
            json[this.name] = this.value || "";
        });
        return json;
        }
    
    // open Modal to view code after submit
    $("#retrieve").click(function(e){
        e.preventDefault();

        var form_inputs = $("#input_form"); //takes input values
        var form_json = convertFormToJSON(form_inputs)
        form_json.submit_button = $("#retrieve").val() //append button type to json

        $.ajax({
            url: "/", 
            type: "POST",
            dataType: "text",
            contentType: "application/json",
            data: JSON.stringify(form_json),
            success: function(data){
                console.log(data)
                $('.modal-body').text(data);
                $('#openModal').modal('show');
            },
            error: function(xhr){
                alert('something broke' xhr)
            }
        })
    });
  });
</script>
  • Related