0

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?

Zheng Liu
  • 292
  • 2
  • 11
  • 1
    Possible duplicate of [How to send JSON instead of a query string with $.ajax?](https://stackoverflow.com/questions/12693947/how-to-send-json-instead-of-a-query-string-with-ajax) – Nick K9 Sep 15 '19 at 07:27
  • @NickK9 Hi Nick. Thanks for making the reference. I understand that `stringify` can be a solution. I'm also aware that there's an option in `ajax` function called `converters`. If I insist on providing a javascript object to `data` instead of the stringified JSON, can I make use of this `converters` field? My intuition is I can use it to convert my data, but I didn't see any documentation about it. – Zheng Liu Sep 15 '19 at 15:18

0 Answers0