I have a button that submits a user input form:
<input class="btn btn-dark" 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);
}
})
});
2
Answers
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:
home.html:
Your server is not expecting JSON data(it’s expecting form-data) so don’t send JSON data, send form data.