user3724786
user3724786

Reputation: 73

Javascript function is only triggered on page refresh

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

Upvotes: 0

Views: 771

Answers (3)

stephenmurdoch
stephenmurdoch

Reputation: 34603

Actually you just need:

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

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

Upvotes: 0

Prakash Subramani
Prakash Subramani

Reputation: 716

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

OR

try

$(document).on 'ready turbolinks:change turbolinks:load'

Upvotes: 1

31piy
31piy

Reputation: 23859

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.

Upvotes: 1

Related Questions