3

I am sending JSON via ajax with the following script:

var dat = {"test":"opa"};
console.log(dat);
$.ajax({
   contentType: "application/json",
   method: "POST",
   url: "/test",
   dataType: "json",
   data: dat,
   success:function(res){
      console.log(res);
   }
 });

But my server receives a query string such as test=opa&foo=bar. What am I doing wrong?

3
  • I think your flask code is fine. Set content = request.get_data() instead and then you can see exactly what the server is receiving. Commented May 5, 2018 at 18:33
  • Could you post the print(response) you are getting? Also, try request.json instead. Commented May 5, 2018 at 18:33
  • With content = request.json it gives me the same 400 error. As the content = request.get_data(), the content printed on the console is the following: b'test=opa'. This does not seem right, and indeed it is not. I just added another parameter to my json in the js and the server seems to be receiving a query string: b'test=opa&foo=bar' Commented May 5, 2018 at 18:55

2 Answers 2

2

When you pass a manually-serialized JSON string, jquery will automatically URLEncode your data.

I suggest you JSON.stringify it

$.ajax({
   contentType: "application/json",
   method: "POST",
   url: "/test",
   dataType: "json",
   data: JSON.stringify(dat),
   success:function(res){
      console.log(res);
   }
 });
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that was it. Had to stringify the object.
0

Its because of your data type. According to http://api.jquery.com/jQuery.ajax/

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is  specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are: 

If you are returning text ("Hi"), you should specify dataType: "text" instead.

2 Comments

That was indeed a mistake I made, seeing that I put the response just for the sake of having one, but it did not fix the 400 error. My server is not being able to process the JSON. The weird thing is, as soon as i switched to request.get_data(), I saw the server was receiving a query string instead.
Sorry, I also forgot to tell you to use JSON.stringify when using dataType "text", as Moses pointed out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.