1

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

1 Answer 1

4

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

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

1 Comment

Got it.i have changed this $('image_url').val(imageURL); to $('#image_url').val(imageURL);

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.