Search code examples
pythonjsonajaxflaskbootstrap-table

Ajax error on Flask web app


I am making a small Flask app. For now, one of the functions I want to implement is that:

  • upload an Excel file
  • do some data cleaning by using pandas
  • show the result dataframe on webpage by using AJAX and also bootstrap-table

I am stuck. Here is my code:

views.py

@app.route('/extract', methods=['GET', 'POST'])
def extract_excel():
  file = request.files['file']

  # SKIP: data extract and transform process, I get a valid dataframe

  df_json = df.to_json(orient="records", force_ascii=False)
  df_json = str(df_json)

  return df_json

index.html

<body> 
<div>
  <form action="/extract" method="post" enctype="multipart/form-data">
    <input type="file" name="file"></input>
    <input type="text" name="upload_date" placeholder="2018-01-01"></input>
    <button type="submit" id="showtable">preview</button>
  </form>
</div>   
</body>
<body>
<table data-toggle="table" id="WorkTable">
    <thead>
      <tr>
        <th>...</th>
        <th>...</th>
        <th>...</th>
        <th>...</th>                               
      </tr>
    </thead> 
</table> 
</body>

<script>
  $(document).ready(function() {
    $('#showtable').bind("click", function(){
        $.ajax({
            type: "POST",
            url: "/extract",           
            dataType: "json",
            success: function (msg) {
                $("#WorkTable").bootstrapTable('load', msg);
            },
            error: function () {
                alert("wrong");
            }
        });
      });
    });  
</script> 

I guess the problem is due to the ajax part. Because I inspected the Console, found POST http://127.0.0.1:5000/extract 400 (BAD REQUEST) appeared very quickly. I guess it should be executed when the file is uploaded and return a response? But I don't know how to fix it.


Solution

  • As noted by Daniel Roseman's comments, you need to send the form data (via the data attribute in the jQuery .ajax call). You'll probably want to have a look at the FormData docs.

    You may also find it useful to make sure you're running with Flask in debug mode so that you get more detailed error messages.