I'm currently facing an issue with POSTing an object to Flask using AJAX. Everything works fine when the object is simple, however, when it contains a nested object, Flask seems to receive the data in an unusual format.
Below is the AJAX POST snippet:
var req = "commit_url";
var data = {"longURL":"www.google.com",
"product":"FIN",
"project":"Zeus",
"platform":"Twitter",
"theme":["Tech"],
"owner":"Tom"};
var submitData = {"req":req, "data":data};
console.log(submitData)
$.ajax({
url: "http://xxx.xxx.xxx.xxx:5000/",
data: submitData,
type: 'POST',
success: function(response) {
var result = JSON.parse(response);
printShortURL(result.shortURL);
},
error: function(error) {
alert("Error contacting the server. See console for details.")
console.log(error);
}
});
Upon submitting the data, the console displays the following output:
{"req":"commit_url","data":{"longURL":"www.google.com","product":"FIN","project":"Zeus","platform":"Twitter","theme":"["#Tech"]","owner":"Tom"}}
Here's the python code in Flask:
@app.route("/", methods=['POST'])
def getData():
f = request.form;
print f
req = f['req'];
print req
longURL = request.form['data[longURL]'];
print longURL
product = request.form['data']['product'];
print product
shortURL = '4Fi92v';
return json.dumps({'status':'OK','shortURL':shortURL});
The response received by Flask looks like this:
ImmutableMultiDict([('data[longURL]', u'www.google.com'), ('data[project]', u'Zeus'), ('data[theme][]', u'#Tech'), ('data[owner]', u'Tom'), ('data[product]', u'FIN'), ('req', u'commit_url'), ('data[platform]', u'Twitter')])
commit_url
www.google.com
xxx.xxx.xxx.xxx - - [06/Feb/2018 12:21:08] "POST / HTTP/1.1" 400 -
Instead of preserving 'data' as an object key, Flask changes it to 'data[project]'. I can access the individual variables but prefer passing the entire 'data' object to another function directly without having to reference each variable separately.
I believe the issue lies within the JavaScript code, and despite attempts with JSON.parse and JSON.stringify, the problem persists.