Juri Glass Juri Glass - 1 day ago 5
Ajax Question

jQuery - How to PUT JSON via Ajax?

I am trying to put some JSON formatted data via Ajax with jQuery to a server. My code looks like this:

$.ajax({
type: "PUT",
url: myURL,
contentType: "application/json",
data: {"data": "mydata"}
});


But on the server-side, I receive a
data=mydata
string, instead of the expected JSON. Firebug tells me the same.

Where is the error?

Answer

I think the data needs to be a String. Objects are converted to querystrings which is what you are seeing here.

You can use the JSON.stringify(obj) method to convert your Object to a String. The code for the JSON object is available from: https://github.com/douglascrockford/JSON-js/blob/master/json2.js.

Alternately, just pass the code you are using to create the object as a literal String, but I imagine this is just an example and you'll want to encode some object you've already created.

Comments