Frage

How to render a partial from javascript with custom locals?

I do have something like this:

var begin = $("#begin_date").val();
var end = $("#end_date").val();

$("#table").html("<%= escape_javascript(render partial: 'my_partial', locals: { begin_date: begin_d, end_date: end_d}) %>")

So, I know that 'begin_d' and 'end_d' must be .erb in order to be loaded. Is there anyway to pass javascript vars in order to render a partial with custom locals values? Or any other way to achieve the same?

My intent is to refresh a table based on the dates (if they are changed).

EDIT:

I found the answer. Phlip helped pointing that I should use Ajax. So now, I made an Ajax request to a controller that simply does:

respond_to do |format| 
  format.html {render partial: 'my_partial', locals: {begin_date: params[:begin_date], end_date: params[:end_date]}}
War es hilfreich?

Lösung

To send JS variables into ERB, you gotta use Ajax. JS runs in the browser, and ERB runs in the server, so there's no way around looking up how to use $('#table').load() there.

Unless if you could do with one of the zillion ways JS can cook its own new HTML, without ERB. The only problem then is you wouldn't be DRY, if you also needed to output that same HTML at page load time, from the server.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top