I am new in rails and ruby, I just started like 1 week ago.
I’m trying to do a chat between 2 people on rails, with jquery for the ajax part.
Everything works, but I got this error that I don’t understand and it really bothers me
Image to the error (couldn’t include it with an image balise)
https://ibb.co/KKjKLPf
VM17:2082 Uncaught Error: If you load both jquery_ujs and rails-ujs, use rails-ujs only.
I understand that I use jquery_ujs and rails-ujs at the same time, and rails want me to only use rails-ujs.
My main page (index.hmtl.erb) has this as code
<h1>welcome to the chat </h1>
<div id='conv'>
<div id='message'>
</div>
<div id='sendmsg'>
<%= form_tag "/", method: "post" do %>
<input type='hidden' name='name' value='phil'/>
<input id='tex' type="text" name="message" />
<input id='sen' type="submit" value="send" />
<% end %>
</div>
</div>
My javascript is like this
window.addEventListener('load', function () {
setInterval(refreshMessage,3000);
function refreshMessage(){
$.ajax({
type: 'GET',
url: '/chatBoard',
success: function(data){
$('#message').html(data);
},
error : function(){
$('#message').html('error');
}
})
};
});
This ajax send to the server a GET to ‘/chatBoard’ and it will return all messages in the database with this script.
<% @messages.each do |message| %>
<%= message.name %> :
<%= message.message %>
<% end %>
I try to find a solution, but I am still stuck so I post it here, I would like to make this work but without this error.
What should I do? Change my ajax request with a CoffeeScript one? Haven’t learned CoffeeScript yet :/
edit:
Hello, i don’t know why but removing something in application.js make the trick
// require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("custom")
i just did a comment on the require(“@rails/ujs”).start() and the error don’t show up anymore and the code still work :/ weard
3
Answers
My guess is in your
application.js
file, you haveIf you remove the
//= require jquery_ujs
, the error should go away.As the error says, you are importing two libraries for the same purpose,
jquery-ujs
, andrails-ujs
. So you need to leave just one depending on the Rails version you are using. If your version is 5.0 or prior to that you need to usejquery-ujs
but if you are using Rails 5.1 onwards you need to userails-ujs
. Additionally, if you need support for jQuery, as you mentioned in the comment, you need to add thejquery-rails
gem in yourGemfile
, runbundle install
in the console, and in theapplication.js
add//= require jquery
(above the line where you are importingjquery-ujs
orrails-ujs
).I would like to add that if I use rails-ujs with jquery-rails, my $.ajax calls only work if I send along the authenticity token!
Plus obviously whatever else is being sent…