How to pass a javascript variable into a erb code in a js view?

fespinozacast picture fespinozacast · Feb 10, 2011 · Viewed 79.7k times · Source

I have this Javascript view in my Rails 3 project:

app/views/expenses/new_daily.js.erb

var i = parseInt($('#daily').attr('data-num')) + 1;
//$('#daily').append('agrego fila ' + i + ' <br />');

$('#daily').append('<%= escape_javascript(render(partial: 'new_expense', locals: { i: i })) %>');

$('#daily').attr('data-num', i);

I want to pass my 'i' javascript variable to a ruby partial through locals, How I can accomplish this?

Answer

Umer Hassam picture Umer Hassam · May 10, 2011

As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server, However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.

a guy asks a similar question Here

and you can learn more about AJAX Here on MDN: