0

This happens in a Rails 5 application with Ruby 2.3.1. When a dropdown list is changed, I want to collect more information via an ajax request to display below the dropdown list. This functionality works, but only if I load or refreshes the page.

app/assets/javascripts/articles.coffee

initGuideline = ->
  $('#article_theme_id').on 'change', (event) ->
    $.ajax
      url: "/themes/guideline",
      type: "GET",
      format: 'js',
      data: {
        theme_id: $("#article_theme_id").val()
      }
$(document).ready initGuideline
$(document).on 'ready page:load', initGuideline

The dropdown list is in a form partial, views/articles/_fields.html.slim, which is called from views/articles/new.html.slim and views/articles/edit.html.slim.

Gemfile

source 'https://rubygems.org'
gem 'rails', '~> 5.0.1'
gem 'sqlite3'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'bootstrap-sass'
gem 'devise'
gem 'slim'
gem 'pundit'
gem 'will_paginate'
and other gems..

assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

When I refresh the page the information is fecthed and displayed. But if I navigate away from the page and navigate back the javascript function is no longer triggered.

The above problem is solved by an answer provided below. The behaviour is caused by Turbolinks and the solution is:

$(document).ready initGuideline
$(document).on 'ready turbolinks:load', initGuideline
mu is too short
  • 426,620
  • 70
  • 833
  • 800
user3724786
  • 63
  • 1
  • 9
  • After the following change, the results are still the same: $(document).ready initGuideline $(document).on 'page:change', initGuideline – user3724786 Feb 20 '17 at 10:11

3 Answers3

1

It happens because of turbolinks, please try to load on page:change instead of ready

OR

try

$(document).on 'ready turbolinks:change turbolinks:load'
Prakash
  • 676
  • 6
  • 22
1

This should have worked fine with Rails 4, but for Rails 5 (with turbolinks 5), you need to use turbolinks:load instead of page:load.

$(document).ready initGuideline
$(document).on 'ready turbolinks:load', initGuideline

Please follow this thread for more details.

Community
  • 1
  • 1
31piy
  • 23,323
  • 6
  • 47
  • 67
0

Actually you just need:

$(document).on 'turbolinks:load', initGuideline

No need to listen for ready because turbolinks:load is fired on ready

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189