Search code examples
javascriptjqueryjson

Setting the POST-body to a JSON object with jQuery


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

Solution

  • You need to stringify your object to turn it into JSON.

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