0

Can I pass values from javascript into rails code ?? Here my example:

<script>
function upload_fun() {
        $.ajax({
            url : '/upload',
            datatype : 'json',
            data :{
                file : file,
            },
            success : function(data_get) {
               console.log(data_get)
               #example: data_get = "1234"
            },
     });
}
</script>
<div>
   #I wan't to put data_get in javascript to rails code like this: 
   <% @data = Data.find_by_dataname(:dataname => "data_get")%>
</div>

Can I pass value like that?

2
  • 2
    No, in short - JavaScript is evaluated at client side (in browser), ERB (html templating in Rails) is evaluated at server side. They are not directly connected. Commented Mar 6, 2015 at 7:57
  • You can create a method in your respective controller to receive value from ajax call. Not sure how you intend to use it Commented Mar 6, 2015 at 8:22

2 Answers 2

0

You can create a method that returns a ready-made HTML and then injecct ($().append()) it into your main file.

There's a guide for working with JS in Rail: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html

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

Comments

0

EDIT: oh you want to do it the other way around :D Well I'll leave this answer anyway, even though it's wrong.

You can store values in data html attribute.

<div id="user" data-name="<%= @user.name %>">
</div>

And then read it using jQuery like this.

var name = $("#user").data("name");

If you are using older jQuery than 1.4.3 you will have to use a bit longer syntax.

var name = $("#user").attr("data-name");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.