Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 317
fespinozacast Avatar asked Feb 10 '11 16:02

fespinozacast


People also ask

How do you pass a variable in JavaScript?

In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

How do you pass a variable in JavaScript Ruby?

One simple solution is to pass the variable as a data attribute. You would run your method, then pass the result with jQuery after the DOM has loaded. This allows you to keep JavaScript in the asset pipeline and pass it data evaluated by Ruby server-side.

How do I pass variables and data from JavaScript to PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result. $result = $_GET [ 'data' ];


1 Answers

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:

like image 50
Umer Hassam Avatar answered Sep 22 '22 04:09

Umer Hassam