Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 961
jbrennan Avatar asked Jun 01 '12 21:06

jbrennan


1 Answers

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

like image 139
Kevin B Avatar answered Sep 20 '22 16:09

Kevin B