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