Laurent
Laurent

Reputation: 1584

Passing javascript variable to partial via render_javascript

I receive a google ID from an Ajax call and then want to use that ID to update a button on my view.

Here is the code in new.js.erb, which is linked to a new.html.erb.

Problem is, I don't know how to pass the variable's content. Restaurant is a json. The alert returns the correct ID and when I search my db on the terminal with the returned google id I find the restaurant.

Here is the code:

alert(restaurant["google_id"]);
    var google_id = restaurant["google_id"];
    $("#rating_bar").html("<%= escape_javascript(render 'reviews/buttons/full_profile_rate_restaurant', :google_id => "+google_id+".html_safe) %>");

What happens is that the variable being passed is the string "google_id" instead of the combination of letters and numbers that is the google ID. I've tried multiple approaches, this is just one of many wrong one - I think this question is pretty easy for anyone who knows their JS really well.

Upvotes: 1

Views: 1487

Answers (1)

Sagar Bommidi
Sagar Bommidi

Reputation: 1409

It is not possible to pass a JS variable to the ruby partial.

As Ryan Bigg explained for the same type of problem here, its not possible to send the variable while rendering that partial. We need to work out some thing else. Even i also had the same issue once.

Alternatively,

if that is google_id is only a variable to display in the partial, then update those divs manually after rendering that partial.

like

$("#rating_bar").html("<%= escape_javascript(render 'reviews/buttons/full_profile_rate_restaurant', :google_id => "sample_id") %>");
// Now update the required elements
$("#what-ever-ids").text(google_id);

or just create some other action in that controller, and call send an ajax request to that action, and there you will have this js variable, and in that js.erb file render the same partial which you actually want to update with the google_id variable.

Upvotes: 3

Related Questions