I am trying to send two pieces of data - a form and an array via AJAX to a Flask endpoint. My javascript with only sending the form is here:
$(document).on('click', '#submit_button', function(){
let form_data = $('#form').serialize();
let other_data = updateOtherData();
req = $.ajax({
url : url_final,
type : 'POST',
data : form_data
});
req.done(function(data){
//does some updates to page here
});
});
And in my flask endpoint this works just fine with doing something like:
@app.route('/process_form', methods=['GET', 'POST'])
def process_form():
form = MyForm()
if request.method == 'POST' and form.validate_on_submit():
#do something here
return some_data_back
However, I would like to send other_data
along with form_data
. So I have tried:
$(document).on('click', '#submit_button', function(){
let form_data = $('#form').serialize();
let other_data = updateOtherData();
req = $.ajax({
url : url_final,
type : 'POST',
data : {'form': form_data, 'other': JSON.stringify(other_data)}
});
req.done(function(data){
//does some updates to page here
});
});
And updated my endpoint to something like:
@app.route('/process_form', methods=['GET', 'POST'])
def process_form():
form = MyForm()
if request.method == 'POST':
form = #Turn this back to a FlaskForm object
other_data = #Just get this as a string
if request.method == 'POST' and form.validate_on_submit():
#do something here
return some_data_back
I have tried a lot of different parts in the above where I cant get it to work. I have tried request.form, request.data, and request.get_json (in which I set contentType in ajax call).
I have looked at many similar questions such as: Get the data received in a Flask request and Get raw POST body in Python Flask regardless of Content-Type header which looked very promising, but everything kept coming across empty.