Rails 4 jQuery, javascript and coffee scripts not working - javascript

I am new to rails and web development, although I have almost two decades of C/C++ in control systems and firmware, and quite a lot of shell and perl scripting.
I can't get jquery to work without explicitly including it, even though it is in the application.js manifest, and I can't get any of the individual coffeescripts to work at all.
Ubuntu 14.04LTS, ruby 2.2.1p85, rails 4.2.0
application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
application.html.erb
<%= render "layouts/header" %>
<%= render "layouts/sidenav" %>
<%= yield %>
<%= render "layouts/footer" %>
_header.html.erb
<html>
<head>
<title>My Application Title</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag 'intranet' %>
<%= stylesheet_link_tag 'form' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>
...
Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'
# Use sqlite3 as the database for Active Record
#gem 'sqlite3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Pagination gem
gem 'kaminari'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Boe
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
I have eleven controllers and views out of 27 built, and they all work well except that I hadn't tried any javascript until yesterday. I wasn't getting any of the expected behavior, so in my "people" index view I added:
...
<script>
$(document).ready(function(){
alert("jQuery is running!");
});
</script>
...
To check and see if jQuery was working at all. If I add <%= javascript_include_tag 'jquery.js' %> before the csrf_meta_tag, I get the alert message but coffeescript and the rest still don't work. Without the explicit jquery include, I get nothing.
I've looked at many, many posts on this, but none of them have worked. It appears to me that the manifest in application.js is not being read and/or the modules listed are not included, except that turbolink appears to work properly gauging by the network panel on the browser when moving from page to page. I removed turbolink and it behaves very differently.
I also tried including the jquery-turbolinks gem, although even though I'm pretty sure it's not needed with the jquery-rails gem. But it doesn't work with turbolinks uninstalled, either, so I don't think that is the conflict.
Thanks for looking.

To resolve this issue I created a blank app with just a 'welcome' controller, containing only the jQuery test script, which worked fine.
Working backwards from the differences in the trees from the naked application, I found that another developer had generated an empty coffeescript file:
app/assets/javascript/application.coffee
I removed this file and the application works properly. The stock javascript_include_tag now reads the manifest and includes the various javascript modules, including jQuery, jQuery-ujs and turbolinks.

Rails 4 automatically adds the sass-rails, coffee-rails and uglifier gems to your Gemfile, which are used by Sprockets for asset compression. So there is no need to add the gem explicitly.
You do not need to add jquery with javascript_include_tag, include your application file instead and let the asset pipeline do its thing. Something like: <%= javascript_include_tag "application" %>

Try adding to config/application.rb
config.assets.enabled = true
You may also want:
config.assets.initialize_on_precompile = true

start your application locally. open your application in any browser. Open the source code of the page. Check if the following line exists
<script src="/assets/jquery.js?body=1" data-turbolinks-track="true">
and if you can see content as follows
/*!
* jQuery JavaScript Library v1.11.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
..........
..........
soon ....
then jQuery works on your application

Related

Application.js is not working as expected in rails 5.2.6 and ruby-2.6.6 with semantic-ui

I am new to ruby on rails. Currently I am using the above specified version of rails and ruby. While following an old ruby on rails course for building a project. I am facing issues with the semantic-ui components. The JavaScript functionality is not working on components with turbolinks. Particularly the flash messages are using "ui message" but it doesn't close on click. Please have a look. I have tried reinstalling semantic-ui and other changes in application.js but still it haven't solved my problem.
1. Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.6'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.6', '>= 5.2.6.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
gem 'semantic-ui-sass'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5.2.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
gem 'hirb'
gem 'jquery-rails', '~> 4.4'
gem 'jquery-ui-rails'
# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
gem 'solargraph'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
gem 'chromedriver-helper'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
2.application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>MessageMe</title>
<%= favicon_link_tag 'favicon.ico' %>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= render 'layouts/navbar'%>
<div class="ui container ">
<%= render 'layouts/messages'%>
<%= yield %>
</div>
</body>
</html>
3.application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//= require jquery3
//=require popper
//= require jquery.turbolinks
//= require jquery_ujs
//= require semantic-ui
//= require rails-ujs
//= require dropdown
//= require activestorage
//= require turbolinks
//= require_tree
$(document).addEventListener('turbolinks:load', function () {
$('.ui.dropdown').dropdown();
$('.message .close').on('click', function () {
$(this).close('.message').transition('fade');
});
})
4.application.css.scss
#import 'semantic-ui';
5.login_form.html.erb
This is the form for my login_page where i am receiving these flash messages.
<%= form_for(:session, html: {class: "ui form", role: "form"}, url: login_path) do |f| %>
<div class="field">
<% f.label :username, "Username"%>
<div class="ui left icon input">
<%= f.text_field :username, placeholder: "Username"%>
<i class="user icon"></i>
</div>
</div>
<div class="field">
<%= f.label :password,"Password" %>
<div class="ui left icon input">
<%= f.password_field :password , placeholder:"Password"%>
<i class="lock icon"></i>
</div>
</div>
<%= f.button "Login", class:"ui blue submit button"%>
<%end%>
this is the login page.
Please pardon me if there are many irregularities or i m using irrelevant libs etc.
Your kind help is appreciated.

Rails jquery can not load in any event

I have tried all the solution in stackoverflow but I still have a trouble with jquery load on rails.It works on localhost but not on heroku.
So, here is my application.js file
//= require jquery
//= require bootstrap
//= require jquery_ujs
//= require_tree .
here is application.css file
*= require_tree .
*/
Here is my gem file;
source 'https://rubygems.org'
gem 'rails', '4.2.0'
gem 'json', '~> 1.8.2'
gem 'bcrypt', '3.1.7'
gem 'bootstrap-sass', '3.2.0.0'
gem 'sass-rails', '5.0.1'
gem 'uglifier', '2.5.3'
gem 'coffee-rails', '4.1.0'
gem 'jquery-rails', '4.0.3'
#//= require turbolinks TO ASSETS gem 'turbolinks', '2.3.0'
gem 'jbuilder', '2.2.3'
gem 'sdoc', '0.4.0', group: :doc
gem "mailboxer"
gem "select2-rails"
group :development, :test do
gem 'sqlite3', '1.3.9'
gem 'byebug', '3.4.0'
gem 'web-console', '2.0.0.beta3'
gem 'spring', '1.1.3'
end
group :test do
gem 'minitest-reporters', '1.0.5'
gem 'mini_backtrace', '0.1.3'
gem 'guard-minitest', '2.3.1'
end
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
end
and here is my application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />
<%= javascript_include_tag 'application', 'data-turbolinks-track' => false %>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track' => false %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
The funny thing is, console does not give an error about jquery but my slider does not work. And some of the css changes did not reflect to heroku (I did precompile)
Since Heroku pre-compiles by default, I'd say the error is likely that you have a "polluted" precompiled assets (when you have maybe 8-10 application.js variants in public/assets).
I could - of course - be completely wrong and will happily remove this post, but you may wish to try:
$ rake assets:clean
$ git add .
$ git commit -a -m "Assets"
$ git push heroku master
$ heroku rake assets:clean
This seems to be an assets compilation issue. For heroku make sure your production environment is well configured, take a look to your /config/production.rb, and make sure you have these configs:
config.serve_static_files = false
config.assets.compile = false
config.assets.digest = true
After check the above configs then make sure your public/assets folder is not in .gitignore.
Then precompile assets in local for then redeploy to heroku, run the following command:
rake assets:precompile RAILS_ENV=production
this may take some minutes, after the process finishes then you can commit and push to heroku:
git add .
git commit -m "Precompiled assets for heroku"
git push heroku master

How to add javascript functions in rails

I am developing my first rails app i have a controller named article that have about 5 action each action with a view page how do i add a JavaScript function for a certain action in the article.coffee file
First thing
Rename your file as action.js.coffee.
Then
Just bind the actions on the elements for your views of action controller.
Well, as detailed on the Rails Guides if you didn't start your projet with the --skip-sprocket option
rails new myapp --skip-sprocket
the asset pipeline should be enable, wich means you should have files looking like this :
Gemfile
...
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
# gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
...
application.html.erb
...
<title>myapp</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
...
If this samples look like your app then just add you JS in the application.js file like this :
...
//= require turbolinks
//= require_tree .
function greatTutorial() {
alert('Rails Guides are the best');
}
and then you'll be able to call this function in your views like this :
<h1 onclick="greatTutorial()">Hello World</h1>
If you want to write in Vanilla JS (meaning basic JavaScript, no Coffee or any preprocessor) make your js files end with ".js", but if you wish to write in CoffeeScript make them end with ".js.coffee" in order to be preprocessed before rendering. I recommend you to read the Rails Guides about the Asset Pipeline wich is a gold mine to understand how Rails deals with the assets. Hope this will help you getting started.

How to add Rails-Jquery back to Rails app?

I'm working with ROR 4. I posted this question about how my link_to wouldn't POST correctly using { method: :post }.
I figured out this was because I removed the Rails-Jquery gem when I first set up my app (this is a side project, I hadn't planned on using Javascript/jQuery or so I thought!).
In an effort to get my POST working, I added the gem back to Gemfile. The file now looks like this:
source 'https://rubygems.org'
gem 'aws-sdk'
gem 'faker'
gem 'jquery-rails'
gem 'inline_svg'
gem 'jbuilder', '~> 2.0'
gem 'nokogiri'
gem 'paperclip'
gem 'pg'
gem 'rails', '~> 4.2.0'
gem 'sass-rails'
I did a bundle install.
I added the below code to application.js:
//= require jquery
//= require jquery_ujs
//= require_tree .
What am I missing? jQuery still isn't loading in the Network tab in Chrome.
I'm guessing I must have changed another config setting on setup (5 weeks ago) that I am now forgetting.
UPDATE: I also removed turbolinks during the main setup. Is that needed for jQuery to work?
If you removed javascript during the initial setup, you are probably missing this from the head of your application.html.erb layout.
<%= javascript_include_tag 'application' %>

Rails first app error -- Errno::ENOENT

I had just installed rails on my windows PC through rails installer -- and i don't know a-lot about rails or anything... after i created my first app (rails new XXX), and created the first controller and view, i ran the server and the first thing i saw was an error:
Errno::ENOENT
Showing C:/Sites/XXX/XXX/app/views/layouts/application.html.erb where line #5 raised:
No such file or directory # unlink_internal - C:/Users/XXX/AppData/Local/Temp/execjs20150402-8140-cy5cjejson
(in C:/Sites/XXX/XXX/app/assets/stylesheets/application.css.sass)
again, I haven't touched my rails ever and haven't written any code yet but still got this error... i searched for hours online for an answer but none of them helped me or solved my problem... I tried installing Node.js, exejs, but nothing helped.
Note:
I have noticed that if i remove
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
in the app template, the website runs normally (but i don't want to remove it -- I need it)
How can i solve this problem?
Edit: my gem file:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
Options:
1) Removing //= require_tree . /Ignoring the issue - As ColinR stated above, this line should not be causing an issue in the first place. There is an actual problem with ExecJS working properly with the JavaScript runtime on your system and removing this line is just ignoring that fact.
2) Installing Node.js / Running away - Many people seem to just end up installing Node.js and using that instead of the JavaScript runtime already on their system. While that is a valid option, it also requires additional software and only avoids the original issue, which is that ExecJS is not working properly with the JavaScript runtime already on your system. If the existing JavaScript runtime on your system is supposed to work, why not make it work instead of installing more software? According to the ExecJS creator, the runtime already built into Windows is in fact supported...
ExecJS lets you run JavaScript code from Ruby. It automatically picks
the best runtime available to evaluate your JavaScript program, then
returns the result to you as a Ruby object.
ExecJS supports these runtimes:
therubyracer - Google V8 embedded within Ruby therubyrhino - Mozilla
Rhino embedded within JRuby Node.js Apple JavaScriptCore - Included
with Mac OS X Microsoft Windows Script Host (JScript) (from
github.com/sstephenson/execjs#execjs )
3) Actually fixing the issue / Learning - Use the knowledge of options 1 and 2 to search for other solutions. I can't tell you how many webpages I closed upon seeing options 1 or 2 was the accepted solution before actually finding information about the root issue we were having. The only reason we kept looking was that we couldn't believe the Rails team would (1) insert a line of code in every scaffold generated project that caused an issue, or (2) require that we install additional software just to run that default line of code. And so we eventually arrived at a fix for our root issue (your miles may vary).
The Fix that worked for us: On the system having issues, find ExecJS's runtimes.rb file. It looks like this. Make a copy of the found file for backup. Open the original runtimes.rb for editing. Find the section that starts with the line JScript = ExternalRuntime.new(. In that section, on the line containing :command => "cscript //E:jscript //Nologo //U", - remove the //U only. Then on the line containing :encoding => 'UTF-16LE' # CScript with //U returns UTF-16LE - change UTF-16LE to UTF-8 . Save the changes to the file. This section of the file should now read:
JScript = ExternalRuntime.new(
:name => "JScript",
:command => "cscript //E:jscript //Nologo",
:runner_path => ExecJS.root + "/support/jscript_runner.js",
:encoding => 'UTF-8' # CScript with //U returns UTF-16LE
)
Next, stop then restart your Rails server and refresh the page in your browser that produced the original error. Hopefully the page loads without error now. Here's the ExecJS issue thread where we originally posted our results: https://github.com/sstephenson/execjs/issues/81#issuecomment-9892952
If this did not fix the issue, you can always overwrite the modified runtimes.rb with the backup copy you (hopefully) made and everything will be back to square one. In that case, consider option 3 and keep searching. Let us know what eventually works for you.. unless it's removing the require_tree or installing node.js, there's plenty of that going around already. :)
Change sass-rails version to 4.0.3 and leave the rest as it is. Remove Gemfile.lock when necessary, and then:
bundle update
bundle install
Finally, don't forget to restart your rails server!

Categories