0

After browsing many solutions which didn't fit or solve my problem I post this question here:

I use javascript to populate hidden fields in a form with data and send it to a rails controller. This works fine with normal variables but I can't get it to work with arrays. This is what I do:

Javascript (jQuery):

$("#my_form").submit(function() {
    var testvar = 5;
    var testarr = [];
    testarr[0] = "test data";
    testarr[1] = "other data";

    $('input[name=testvar]').val(testvar);
    $('input[name=testarr]').val(JSON.stringify(testarr));
})

RoR controller:

def create
    testvar = params[:testvar]
    data = params[:testarr]
    testarr = ActiveSupport::JSON.decode(data)
    // other commands
end

It works fine for testvar but for the array it always creates the error

can't convert nil into String

What am I doing wrong?

The request looks like this:

{"utf8"=>"✓",
 "authenticity_token"=>"1qFA3NTqUxoI1jusbwrVi5AWIpJz9tbUGR0KuCtNKTs=",
 "testvar"=>"5",
 "testarr"=>"[\"test data\",
 \"other data\"]",
 "commit"=>"Submit my form data"}

Thanks in advance, your help is highly appreciated!

1 Answer 1

1

If you name your input fields with [] at the end, rails will map it to params as an array

<input type="hidden" name="testarr[]" />

$(....).val(testarr.join(","))

Or append a new input for each instead of join, they all have the same input name

$(....).submit(....
  $form = $(this)
  testarr.each
    $form.append('<input type="hidden" name="testarr[]" value="...itemValue..." />')

In controller

params[:testarr].each do ....

Typed on an ipad, please forgive incomplete code, hopefully it gives you some ideas

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

1 Comment

I was actually doing this last night and just split on ',' in the controller but obviously this is much better. Awesome!

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.