1

Hi I am calling a partial from controller file but the javascript inside the partial is not executing . The partial is of .html.erb format.

<% content_for :javascript do %>

  <script type="text/javascript">
    var eventName = typeof(Turbolinks) !== 'undefined' ? 'page:change' : 'DOMContentLoaded';

    document.addEventListener(eventName, function() {
      console.log("hello");


      <% if flash[:notice] %>
        ShopifyApp.flashNotice("<%= escape_javascript flash[:notice].html_safe %>");
      <% end %>

      <% if flash[:error] %>
        ShopifyApp.flashError("<%= escape_javascript flash[:error].html_safe %>");
      <% end %>
    });
  </script>
<% end %>

is the code for partial

 respond_to do |format| 
    if @timer.save



      flash[:notice]="updated"
      format.html{render :partial => "layouts/flash_messages", :locals => {:flash => flash}}





    else
        flash[:error]="error"
      format.html{render :partial => "layouts/flash_messages", :locals => {:flash => flash}}
    end

is the controller code .

2
  • 2
    That partial doesn't render anything, it just adds the javascript to the :javascript content store. Usually this content_for technique has a corresponding <%= yield :javascript %> or <%= content_for :javascript %> elsewhere in a layout. Commented Dec 6, 2017 at 21:08
  • Thanks Aaron Breckenridge going to try yeild :) Commented Dec 7, 2017 at 6:23

1 Answer 1

2

If you want to render Javascript in rails use below method.

Controller Code looks like:

def create
  @user = User.find(params[:id])
  respond_to do |format|
    format.html {redirect_to @user }
    format.js
  end
end

template this code going to render will look like.

filename: create.js.erb

 $("#someidname").html("<%= @user.email %>");

Note @user is also available here. you can render other partial also like:

$("#someit").html("<%= escape_javascript(render('users/email')) %>");

Also, make sure you are sending ajax request.

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

Comments

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.