amtest
amtest

Reputation: 700

Passing a javascript variable into a rails controller

I need to pass one javascript variable into a rails controller. Here is my app code:

view.html.erb

<script type="text/javascript">
    var imageURL;
    var sCode = function () {
        $("#qr").html("<p align='center'><img src='https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=123&choe=UTF-8'/></p>");   
        imageURL = "https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=123&choe=UTF-8";
    }
</script>

<div class=" modal-body" id="qr"> 
</div>

<div class="modal-footer" id="footer">
    <%= form_tag({:controller => 'branches',:action => 'mailme' }, {:method => :post})  
    do %>
        <%= submit_tag  "Mail", :id => "mailme", :class => "btn btn-primary pull-left" %>
    <% end %>
</div>

Here I need to pass the imageURL variable to method mailme from controller branches. How can I get that variable? I have tried to attach that variable with submit_tag and also tried hidden_filed_tag to get that, but nothing worked.

Thanks

Upvotes: 1

Views: 851

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

You have to use javascript to manipulate a hidden field tag that will be submitted in the form.

Form :

<%= hidden_field_tag "image_url" %>

JS :

<script type="text/javascript">
    var imageURL;
    var sCode = function () {
        $("#qr").html("<p align='center'><img  src='https://chart.googleapis.com/chart?  
        chs=250x250&cht=qr&chl=123&choe=UTF-8'/></p>"); 
        imageURL = "https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=123&choe=UTF-8";
        $('#image_url').val(imageURL);
    }
</script>

Of course you'll have to execute the function declared in sCode somehow.

In the controller, just access params[:image_url] to get the URL

Upvotes: 4

Related Questions