0

I want to display the SQL code returned from various input parameters as a Modal. I am having trouble getting the POST request made from inputs to show up in the Modal upon pressing the submit button. I've been reading that this type of process usually invovles Ajax but how do I get ajax to get the POST data from flask?

routes.py:

if request.method == "POST":
    submit_button = request.form["submit_button"]

    if submit_button == "View Data":
       DO SOMETHING

    elif submit_button == "View Code":
        sql_code = <class to get sql code>
        return render_template("home.html", sql_string=sql_code)

return render_template(
    "home.html",
)

home.html:

 <form action="/" method="POST" onsubmit="openModal()" id="userinputForm">    
     <div class="filters">
        <!-- Input fields -->
        ... INPUTS FIELDS GO HERE
        
        <!-- Submit Button --> 
        <input class="btn btn-dark" type="submit" name="submit_button" value="View Code">
        
        <!-- Modal -->
        <div class="modal fade" id="sqlModal_submit" tabindex="-1" role="dialog" aria-labelledby="sqlModallLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
              <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">SQL Code</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    <p>{{ sql_string }}</p>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
              </div>
            </div>
        </div>

        <script>
            $('#userinputForm').on('submit', function(e){
            $('#sqlModal_submit').modal('show');
            e.preventDefault();
            });
        </script>
    </div>
</form>

1 Answers1

0

Instead of return render_template() which tells flask to display a template, you should return json data.

You can try

output= {"sql_string": sql_code}
return app.response_class(json.dumps(output), content_type="application/json")

or you can do

output= {"sql_string": sql_code}
return jsonify(output)

Then you have to 'catch' the returned data in your javascript code (the one that submitted the form). See this stackoverflow response for a sample

NoCommandLine
  • 5,044
  • 2
  • 4
  • 15
  • I'm having a hard time figuring this out, I can' seem to figure how out how to open the Modal with the "catched" return data inside of it. – WhimsicalWhale May 19 '22 at 00:33