2

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]}}
2
  • To clarify, do you want to insert values of JS variables into the table instead of the values that server has sent? Commented Jan 25, 2014 at 0:44
  • No. I want to pass JS values to render a partial with that JS values. I mean, editing an input value (begin or end date) I want to trigger the render of a partial. The render of that partial depends on the JS values I get from the input. Hope it clarifies. Commented Jan 25, 2014 at 0:52

1 Answer 1

1

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.

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

2 Comments

Thanks. In this particular case, it won't be rendered at page load time, so that wouldn't be an issue, but I don't want to cook up new HTML (I had another code where I wanted to keep it DRY and couldn't because I didn't know the 100% right path). Can you help me in the following? I do pass the vars with ajax to a controller, right? But then, what do I do?
From here, nearly any google search for citation [rails jquery ajax example] will be enough to get you started.

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.