I have a HTTP server built using Python Flask, which serves an API as a backend, and a webpage which calls the API using JQuery ajax. When I make a POST request, I got some parsing problem on the server site. My JQuery POST looks like the following.
$.ajax({
method: "POST",
url: "<API endpoint, on same server>",
data: <a javascript object>, //yes, this is the cause of the problem
dataType: "json",
contentType: "application/json"
}).done(func_success).fail(func_error);
Notice that the data field was given a javascript object. At first I thought if I specified contentType to be application/json, the ajax function will make the data into a JSON format. However, a simple print on the server revealed it was not the case. The contentType field is only responsible to set the Content-Type header. By default, JQuery always converts a plain javacript object to url-encoded format, regardless of the dataType parameter given.
As a walkaround, I used JSON.stringify(data) to serialize the javascript object to a JSON string. However, I wonder whether there is a better practice to use ajax function. If you are to POST a javascript in JSON format using JQuery, how would you do that?