views:

30

answers:

4

Trying to get JQuery to post JSON to a server:

$.ajax({  
  url: "/path/to/url",  
  type: "POST",  
  dataType: "json",  
  contentType: "json",  
  data: {"foo": "bar"},  
  success: function(){              
    alert("success :-)");  
  },  
  error: function(){  
    alert("fail :-(");  
  }  
});  

Problem is the data appears on the server as "foo=bar" rather than the desired "{\"foo\":\"bar\"}.

I thought specifying either the dataType or contentType params would do the trick, but no.

Anyone know the correct ajax configuration ? [or alternatively a way of serialising the 'data' parameter as JSON prior to posting ?]

Thanks!

A: 

Looks correct to me. "foo=bar" is HTTP POST standard format of passing variables in. If you want to use a different format, you may need to wrap the "{foo:bar}" in a HTTP POST variable. Something like "json={foo:bar}".

Adrian Godong
+1  A: 

You could use json2.js:

data: JSON.stringify({"foo": "bar"})
Darin Dimitrov
A: 

Datatype is for returned data. Contenttype is not applicable, see here

It can only send strings, I use JSON.stringify on my created javascript objects, in your case you could just manually code the string.

You will also need to access the string on server side, for that if you are using java I can recommened google's gson

NimChimpsky
A: 

Umm...

$.ajax({  
  url: "/path/to/url",  
  type: "POST",  
  dataType: "json",  
  contentType: "json",  
  data: {"foo": "bar"},  
  .
  .
  .
});

The above jQuery code tells the browser that it should post the data foo=bar to /path/to/url and expect the server to return JSON and interpret the response accordingly. The server script will receive a value of "bar" the in the post variables collection (e.g. $_POST["foo"] in PHP or Request.ServerVariables("foo") in classical ASP). The above answers are correct in the sense that you have to convert the JSON data into a string and dispatch it to the server script. You can then de-serialize the data on the server.

Salman A