Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: $ is not defined rails

I'm trying to add Froala editor to my project.

Problem only on production server(on localhost it works fine) I'm using rails 4.1.0 In gemfile i'm have

gem 'jquery-rails'

In my assets/javascripts/application.js:

//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .
//= require modernizr
//= require froala_editor.min.js

In new.html.erb file:

<div class="row">
  <%= form_for :article do |f| %>
    <p>
        Title<br>
        <%= f.text_field :title %>
    </p>
    <p>
        Content<br>
    <%= f.text_area :text, :id=>'content' %>
    <p>
    <%= f.submit %>
    </p>
  <% end %>
</div>
<script>
  $(function() {
    $('div#content').editable({
      inlineMode: false
    })
  });
</script>

In application.html.erb:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
    <title><%= content_for?(:title) ? yield(:title) : "foundation-rails" %></title>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag "vendor/modernizr" %>
    <%= javascript_include_tag "application" 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

In this case result is:

Uncaught ReferenceError: $ is not defined

If i'm adding a string:

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

result is:

Uncaught TypeError: undefined is not a function
like image 903
bartezr Avatar asked Mar 29 '15 08:03

bartezr


2 Answers

The following is what I needed to do for Rails 6 (6.0.3.4 to be exact.) [found at (all credit goes to): https://www.botreetechnologies.com/blog/introducing-jquery-in-rails-6-using-webpacker]

  1. Add jQuery to environment. $ yarn add jquery

  2. Add below code in environment.js (<app_path>/config/webpack/environment.js)

     const webpack = require('webpack')
     environment.plugins.prepend('Provide',
     new webpack.ProvidePlugin({
         $: 'jquery/src/jquery',
         jQuery: 'jquery/src/jquery'
     })
     )
    
  3. Require jquery in application.js file. (/app/javascript/packs/application.js) require('jquery')

  4. (Restart rails server to make sure everything gets loaded.)

like image 109
Mark Wicker Avatar answered Sep 21 '22 09:09

Mark Wicker


This was my solution:

Put this in your app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs

and install this gem file:

gem 'jquery-rails'
like image 42
jasmineq Avatar answered Sep 20 '22 09:09

jasmineq