I am trying to POST an object to Flask using AJAX. When the object is simple the code works fine but when when the object includes a nested object Flask receives the data in a weird format.
Here is the AJAX POST:
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);
}
});
When I submit the data the console shows this:
{"req":"commit_url","data":{"longURL":"www.google.com","product":"FIN","project":"Zeus","platform":"Twitter","theme":"["#Tech"]","owner":"Tom"}}
Here is the python 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});
Here is the result that I get in Flask:
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 -
As you see it's changing the key to 'data[project]' rather than preserving 'data' as an object. I can access the data but I would like to be able to pass the whole 'data' object to another function without having to go through all the variables.
I'm pretty sure the problem is with the javascript but I tried using JSON.parse and JSON.stringify but I've had no success.