Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null in AJAX request Rails interprets it as "null"

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.

like image 807
Gerry Avatar asked Sep 17 '25 17:09

Gerry


1 Answers

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".

like image 190
Gerry Avatar answered Sep 20 '25 08:09

Gerry