5

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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"
});

3 Comments

Actually, jquery serialize the passed data in default.
@knoguchi - yep - jQuery.param is what jQuery uses to serialize the object. I was just wondering if doing the serialization elsewhere (rather than .ajax doing it itself) would help solve the problem.
Thanks for the suggestion. I have tried serialize manually as you suggested but it did not change anything unfortunately.
0

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/

1 Comment

Thanks for the answer. I have already tried not deserializing it but it wasn't the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.