I am trying to send an AJAX request via the $.ajax to a Rails 3 backend and I am stuck to a weird behavior. Take for example the following request:
$.ajax({
url: $(this).attr('href'),
type: 'PUT',
dataType: "json",
data: {a: null},
success: function (data) {
console.log("success!")
}
});
which I am binding to a click event. Simple. What is happening is that Rack parses the URI encoded form parameters as {"a" => "null"}
and I really want to get parsed as {"a" => nil}
. Is there any non-hackish way to achieve this behavior?
Thanks a lot!
P.S. If I pass {a: undefined}
then params hash has no a
key at all.
Ok I found the solution to this. I had to change the $.ajax
call to this:
$.ajax({
url: $(this).attr('href'),
type: 'PUT',
dataType: "json",
contentType: "application/json",
data: JSON.stringify({a: null}),
processData: false,
success: function (msg) {
console.log("success!")
}
});
which does two important things. First it passes the content type header to JSON in order the request payload to automatically get parsed as JSON by Rack. The other one is that processData
must be set to false in order to prevent the default jQuery behavior:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With