katsuya
katsuya

Reputation: 1204

How to send json request to rails using jquery

I would like to send JSON post request to rails 3 server. I have following ajax request:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: {email: "[email protected]", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});

However the rails server receive the data as following:
{"_json"=>["object Object"]}
Where I want it to receive it as:
{"email"=>"[email protected]", "password"=>"[FILTERED]"}

I think this is happening because the jquery wraps the data with _json object if the content type is json.

Does anybody know how I should do this?

Upvotes: 5

Views: 6197

Answers (3)

katsuya
katsuya

Reputation: 1204

This turns out to be because of bugs in old version of jquery. I now user jquery version 1.5 and send post request as follow:

$.post(url, { email: emailVal, password: passwordVal }, callback, "json").error(errorHandler);

It now works perfectly fine.

Upvotes: 4

Chris Bailey
Chris Bailey

Reputation: 4136

have you tried doing the serialization yourself (using jQuery.param)?

jQuery.param({email: "[email protected]", password: "password"})
==> "email=example%40test.com&password=password"

So that your ajax request becomes:

$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: $.param({email: "[email protected]", password: "password"}),
success: onSuccess,
error: onError,
dataType: "json"
});

Upvotes: 2

eggie5
eggie5

Reputation: 1960

According to jquery docs it seems like if you pass in an object to data it will try some automatic deserialization.

Set processData: false and then set data to json string.

http://api.jquery.com/jQuery.ajax/

Upvotes: 0

Related Questions