0

The question

My javascript isn't being called following a redirect_to. Is this expected? Is there a way to make it get called?

The controller

# file: app/controllers/widgets_controller.rb
class WidgetsController < ApplicationController

  # GET /widgets
  def index
    @widgets = Widget.order(:id)
  end

  # GET /widgets/refresh_all
  def refresh_all
    @widgets = Widget.order(:id)
    @widgets.refresh_all
    redirect_to :widgets
  end

end

The view

In /app/views/widgets/index.html.erb:

<p>Widgets are <%= @widgets.any_refreshing? ? "" : "not" %> being refreshed.</p>
<script type="text/JavaScript">
  $( window ).load(function() {
      console.log( "...C" );
  });
  $( document ).ready(function() {
      console.log( "...B" );
  });
  console.log("...A" );
</script>

What I observe

When I access the page via GET /widgets, the javascript is triggered and I see "...A\n...B\n...C\n" on the console. When I access the page via GET /widgets/refresh_all, the page is correctly rendered ("Widgets are being refreshed"), but nothing in the javascript is called.

Is this perhaps because I'm doing a redirect_to :widgets in my controller?

What am I missing?

fearless_fool
  • 33,645
  • 23
  • 135
  • 217

2 Answers2

1

Not exactly sure what's happening but had something similar.

Your js is loading and running before the dom is done loading. Try callng the js once the dom has loaded. Try $(document).ready in jquery or similar.

When you refresh, the dom and assets are cached so the js runs at the correct time.

fnln
  • 220
  • 3
  • 7
  • 1
    thanks for the answer -- I tried your solution and realized that no js code was being called at all. So I've pretty much rewritten the original question to reflect that. But I give you a +1 for helping me narrow the problem. – fearless_fool Dec 15 '14 at 02:35
0

It turns out that Turbolinks was inhibiting the call the the javascript following a redirect for reasons I don't fully understand. FWIW, it was also inhibiting meta refreshes as well. (Perhaps an expert could chime in on why...)

Anyway, the fix was to add a

<body data-no-turbolink="true">
  ...
</body>

on pages where Turbolinks are to be disabled. See https://stackoverflow.com/a/22327275/558639 for more info.

Community
  • 1
  • 1
fearless_fool
  • 33,645
  • 23
  • 135
  • 217