Ask A Question

Notifications

You’re not receiving notifications from this thread.

'Uncaught ReferenceError: Rails is not defined' even after importing it in application.js file

anujmohatkar asked in Javascript

hello, i am really new to Rails. I wanted to make ajax call to a function in controller.
I have following in my view:

function fetchMessages() {
  // Get user input from text field
  let input = $("#userInput").val;
  // Make Ajax request to fetchMessage endpoint
  Rails.ajax({
    url: "/chat/fetchMessage",
    type: "get",
    data: "input=" + input,
    dataType: "html", // Specify the format of the response
    success: function (data) {
      // Append response to chat area
      let chatArea = document.getElementById("chat-area");
      let response = document.createElement("p");
      response.innerHTML = data;
      chatArea.appendChild(response);

      // Scroll to bottom of chat area
      chatArea.scrollTop = chatArea.scrollHeight;
    },
    error: function (data) {
      // Handle error
      alert("Something went wrong!");
    },
  });

and in my application.js file has rails and jquery imported.


import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
import $ from 'jquery';

Rails.start()
Turbolinks.start()
ActiveStorage.start()

and following in my config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Rails: '@rails/ujs'
  })
)


module.exports = environment

i have also done yarn add '@rails/ujs' and have <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %> in my layout file.
but i am still getting the error as 'Uncaught ReferenceError: Rails is not defined'
This is a rails 6 app.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.