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?

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
luz.arthur
  • 135
  • 7
  • I think your flask code is fine. Set `content = request.get_data()` instead and then you can see exactly what the server is receiving. – Alex Hall May 05 '18 at 18:33
  • Could you post the print(response) you are getting? Also, try request.json instead. – Drugo May 05 '18 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'` – luz.arthur May 05 '18 at 18:55

2 Answers2

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);
   }
 });
Moses N. Njenga
  • 762
  • 1
  • 9
  • 19
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.

Drugo
  • 169
  • 3
  • 14
  • 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. – luz.arthur May 05 '18 at 18:53
  • Sorry, I also forgot to tell you to use JSON.stringify when using dataType "text", as Moses pointed out. – Drugo May 05 '18 at 20:17