tags:

views:

522

answers:

4

Hi

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

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

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

Where is the error?

A: 

Do something like this

$.ajax({
          type: "PUT",
          dataType: "json",
          data: dataString,
          url: 'yourUrl'
        });

dataString should be somthing like: 'test/case&id=1&topic=new'

Kennethvr
he said PUT; switching HTTP methods won't magically make the params appear as JSON on the server.
just somebody
The dataType option tells AJAX how to intepret the results, not how to send the data.
tvanfosson
A: 

No error. It is taking the object and converting it to form parameters, just like it should. Most likely, you simply need to change your code to accept these as form parameters instead of JSON. If it really must be JSON, you can investigate using the contentType option and see if changing to another content type (maybe text/plain) would help. Personally, I'd stick with the form-encoded parameters.

tvanfosson
+3  A: 

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: http://www.json.org/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.

Andy
This is the way @Juri should go if he wants JSON on the server. I use the json2.js library all the time and it works great.
Doug Neiner
A: 

the error is in your expectations. the object literal gets encoded to whatever is appropriate for the HTTP method in question. if you want to see JSON on the server, you'll need to serialize the data on the client. BTW, PUT is meant for file uploads, if you're not using it that way, you're breaking the "semantics" in "semantic web".

just somebody
The standard doesn't say anything about file uploads with regard to PUT. It's very vague about what an entity is and what it means to store the entity. In a RESTful setting, PUT is a natural choice for a create action and would be preferred if all browsers actually supported it.
tvanfosson
When method is set to `PUT` in jQuery it still sends it as `POST`, but I think it adds `_method=put` to the query string for compatibility with Rails and other frameworks.
Doug Neiner