user2452057
user2452057

Reputation: 916

Access rails params hash in jquery

Is it possible to access Rails params hash in jquery? I need to add one more key(which is nothing but a column in the table) to params before submit of a form.

$('#form_id').submit(function() {
        // do some manipulation to get key
        params[key] = value;
        // params in rails hash 
        $('#form_id').submit();
 });

Is this possible?

Upvotes: 2

Views: 3300

Answers (2)

dgilperez
dgilperez

Reputation: 10796

Yes, it's possible.

Just add that jQuery code to your template and call params like this. I don't know what do you want to do exactly so I just show how to access the params hash.

Haml version:

:javascript
  console.log "#{j params[:key]}";

ERB version:

console.log "<%= j params[:key] %>";

Upvotes: 1

fny
fny

Reputation: 33587

You can assign the value of a param to a variable in JavaScript, but you'll need to be sure to escape the param to prevent possible XSS attacks.

<script>
  var key = "<%= j(params['key']) %>";
</script)>

...but you probably don't need to use JavaScript. If you're trying to submit one of the params along with the form, you can easily pass it using a hidden form element:

<input type="hidden" name="column" value="<%= j(params['key']) %>">

This will result in param[:column] being set to the given param value upon form submission.

Upvotes: 5

Related Questions