20

I'm trying to write a JSON-based web API in a Sinatra app. I want to POST a JSON object as the post body (with the proper content-type set) but I'm struggling.

In Cocoa, I'd do something like

[mutableHTTPRequest setHTTPBody:dataRepresentationOfJSONObject];

And the content type, set to JSON, would then post the HTTP body as a JSON object. I'm trying to do this with jquery. The best I can do so far just takes the JSON object and turns it into a normal style key=value&… style post body, and that's not what I'm after.

My Javascript:

var data = { "user" : "me!" };
$.ajax({
    type: "POST",
    url: "/api/user/create",
    contentType: 'application/json',
    data: data,
    success: function(r) {

});

Any pointers on how to do this? My goal is for my Sinatra to do like the following

post "/api/user/create" do
    js = JSON.parse(request.body.read)
    # do something with the js object… this works when POSTing from Cocoa
end
jbrennan
  • 11,943
  • 14
  • 73
  • 115

1 Answers1

54

Add the processData parameter to your ajax request and set it to false. Additionally, you need to stringify your object to turn it into JSON.

var data = { "user" : "me!" };
$.ajax({
    type: "POST",
    url: "/api/user/create",
    processData: false,
    contentType: 'application/json',
    data: JSON.stringify(data),
    success: function(r) {
    }
});

JSON.stringify will not work in older versions of IE unless you implement it. http://json.org

Grim
  • 1,938
  • 10
  • 56
  • 123
Kevin B
  • 94,570
  • 16
  • 163
  • 180