How to send json request to rails using jquery

I want to send a JSON request to rails 3 server. I have the following ajax request:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: {email: "example@test.com", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});

However, the rails server receives the data as follows:
{"_json"=>["object Object"]}
Where I want it to receive it as:
{"email"=>"exmaple@test.com", "password"=>"[FILTERED]"}

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

Does anyone know how I should do this?

+5
source share
3 answers

This happens due to bugs in the old version of jquery. I am now a jquery user version 1.5 and will send a request for a message as follows:

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

Now it works great.

+4
source

( jQuery.param)?

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

, ajax :

$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: $.param({email: "example@test.com", password: "password"}),
success: onSuccess,
error: onError,
dataType: "json"
});
+2

According to jquery docs, it seems that if you pass an object to data, it will try to do some automatic deserialization.

Install processData: falseand then install the data in json string.

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

0
source

All Articles