fearless_fool
fearless_fool

Reputation: 35159

javascript not being called after a redirect_to

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?

Upvotes: 0

Views: 58

Answers (2)

fearless_fool
fearless_fool

Reputation: 35159

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.

Upvotes: 0

fnln
fnln

Reputation: 230

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.

Upvotes: 1

Related Questions