Rails Authenticity Token not valid when using a different layout - ruby-on-rails

I have a rails app that uses a modal to post data to a controller and save it to the database. The flow works perfectly when using my old "original" layout, but after implementing a new bootstrap-themed layout, when I try to submit that I get an invalid CRSF error.
If I change the layout on the controller back to the original, it works just fine.
The JS that runs that click/post method is the following:
$(document).on("click",".clickable", function(){
var link = $(this).data('link')
console.log(link);
$.ajax({
url: link,
type: "POST",
});
});
Nothing in the code is changing other than the layout for the controller and like I mentioned, if I change the layout back to the original one, it works just fine. Could I be missing a javascript file or something else in the new layout's javascript?
New layout js file: stack.js
//= require jquery3
//= require popper
//= require rails-ujs
//= require bootstrap
//= require stack/vendors/vendors.min
//= require stack/vendors/charts/raphael-min
//= require stack/vendors/charts/morris.min
//= require stack/vendors/extensions/unslider-min
//= require stack/vendors/timeline/horizontal-timeline
//= require stack/core/app-menu
//= require stack/core/app
//= require stack/scripts/pages/dashboard-ecommerce
//= require_tree ./common
Old layout js file: application.js
//= require jquery3
//= require popper
//= require rails-ujs
//= require bootstrap
//= require_tree ./common
All js files specific to the new template are in a "stack" folder under the javascripts main folder which is why only ./common is included above. I did not want all files under stack to be included since there are a lot of files I have not connected or removed yet.
Any thoughts?
Error:
Started POST "/add_interest?city_id=59020&name=Mission+District%2C+San+Francisco%2C+California%2C+US&region_id=128085&type=region" for 127.0.0.1 at 2019-02-16 13:30:02 -0800
Processing by InterestsController#create as */*
Parameters: {"city_id"=>"59020", "name"=>"Mission District, San Francisco, California, US", "region_id"=>"128085", "type"=>"region"}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken:
`

Since you are using Rails-ujs, you can use it's ajax method that already handles the token for you:
https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts/rails-ujs/utils/ajax.coffee#L15
$(document).on("click",".clickable", function(){
var link = this.dataset.link;
console.log(link);
Rails.ajax({
url: link,
type: "POST",
});
});

Try like this:
$(document).on("click",".clickable", function(){
var link = $(this).data('link')
console.log(link);
$.ajax({
url: link,
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
method: "POST",
dataType: "json",
data: {}
});
});

Related

form_tag remote true not processing as json request rails 5

I have a form in my application as this
<%= form_tag(studios_path, method: :get, id: "studios_filter", remote: true) do %>
<% end %>
in my application.js, i have this
//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require jquery3
//= require turbolinks
//= require cocoon
//= require bootstrap
//= require_tree .
Both somehow whenever this form is submitted, i get it as this
Started GET "/studios?utf8=%E2%9C%93&workout_category_id_list=&neighbourhood_list=Kuala+Lumpur&studio_id_list=" for 127.0.0.1 at 2018-12-28 12:42:12 +0800
Processing by StudiosController#index as HTML
It is processing as HTML instead of processing as JSON since remote: true is already added.
Any ideas as to why this happening. Running out of options
As per the description mentioned in the post it seems like you are concerned with the expected request type("json") not being sent over the controller.
So, for it work as mentioned in the post, change the code as below:
<%= form_tag(studios_path, method: :get, id: "studios_filter", remote: true, :html => {:'data-type' => 'json'}) do %>
This will be processing the request as json type.
since you are using method: :get in your form, all the form values get appended to the studios_path, you must use this method aspost and change the method in routes to post. After that you will start getting all the form fields in your controller as a hash
I struggled with the same issue: Rails 5 was processing my remote: true form submits as HTML no matter what I did. The solution for me was to add
//= require jquery_ujs
to application.js. OP already has this in their file above, which is what made me give it a try. Not sure why OP is still having issues, but this solved it for me ... so maybe this'll solve it for others!

Rails 5 and select2 error, select2 is not a function

I am trying to use the rails select2 gem, gem 'select2-rails'
But when I try to use it with the following order import order, my browser complains that select2 is not a function. From what I have found this order should be correct.
javascripts/application.js
//= require rails-ujs
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require select2-full
//= require_tree .
$(document).on('turbolinks:load', function() {
console.log('(document).turbolinks:load')
$("#estimation_patient_id").select2({
theme: "bootstrap"
});
});
You can use
//= require rails-ujs
OR
//= require jquery_ujs
not needed to both
And modify like below
(function($){
$(document).on('turbolinks:load', function() {
$("#estimation_patient_id").select2({
theme: "bootstrap"
});
});
}(jQuery));
Remember it: sometimes //= require select2-full is not working but //= require select2 is working nicely with all requirements. I recommend to use //= require select2.

Bootstrap Tooltip in Ruby on Rails

I'm trying to get this done for quite some time now and i can't figure out whats wrong:
My Link:
<%= link_to '#', tag, class: "tag-tooltip",
:data => {:toggle=>"tooltip"},
'data-original-title' => "Hey Whats up",
'data-placement' => 'right'%>
My Javascript:
$('.tag-tooltip').tooltip();
But it's not working... What am i missing ?
EDIT
If i go into my Chrome Console and insert ($('.tag-tooltip').tooltip();) it is working.
So i guess the js file is not loading ? (I checked my application.js and i'm requiring everything.)
I found out the wrapping which worked:
$(document).on("ready page:change", function() {
$('.tag-tooltip').tooltip();
});
Update:
$(document).on("turbolinks:load",function(){
$('.tag-tooltip').tooltip();
})
With vanilla JS
document.addEventListener("turbolinks:load", function() {
$('.tag-tooltip').tooltip();
});
In my case the problem was that I was loading jquery-ui after bootstrap-sprockets
In my application.js I changed:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require jquery-ui
to
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require turbolinks
//= require bootstrap-sprockets
Then it all started working as it should.
You need to add some script in your code :
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip(
{container:'body', trigger: 'hover', placement:"right"}
);
});

Uncaught Error: No module: app angularjs and rails

I am new to angularjs I am trying simple app by referring some startup tutorials
When i run my app getting error as
Uncaught Error: No module: app
Here is my controller
club-controller.js
'use strict';
var app = angular.module('app');
app.controller('ClubsIndexController', ['$scope','Club','$routeParams', function($scope, Club, $routeParams){
$scope.clubs = Club.query();
}])
models.js
'use strict';
var app = angular.module('app');
app.factory('Club', function($resource){
return $resource("clubs/:id", {id: '#id'},{
index: {method: 'GET', isArray: true, responseType: 'json'}
});
})
Here is my app.js.erb
'use strict';
angular.module('app', ['ngResource'])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/', {controller: 'ClubIndexController', templateUrl: '<%= asset_path('templates/index.html') %>'})
}]);
I couldn't understand what is happening here. Can anyone help.
Edit-1
Changed my application.js file as
//= require jquery
//= require jquery_ujs
//= require angular
//= require ../angular/app.js
//= require_tree ../angular
But now getting error as Uncaught Error: No module: ngResource
The app.js file must be included before models.js or club-controller.js.
The module definition angular.module(name, [dependencies]) will create the module for you. The other usages angular.module(name) will get the module, and expects it to have been defined with dependencies already.
you have add in aplication.js require angular-resource.
//= require jquery
//= require jquery_ujs
//= require angular
//= require angular-resource
//= require ../angular/app.js
//= require_tree ../angular

Ember data find method on application ready

I'm building an Ember application using ember-data and rails as an API. I'm trying to call a find method on a BusinessNotifications model from the application.js file. When making the initial call I get the "has no method 'find'" error.
My application.js file:
//= require jquery
//= require jquery_ujs
// require jquery.ui.all
//= require handlebars
//= require ember
//= require ember-data
//= require ember-auth
//= require_self
//= require auth
//= require company_backend
//= require ./wepay
//= require_tree .
//= stub polyfills/aight.js
//= stub polyfills/aight.d3.js
//= stub polyfills/mediaqueries.js
//= stub polyfills/pointerevents.js
//= stub polyfills/svg.js
window.CompanyBackend = Em.Application.create({
ready: function() {
var BusinessNotifications = CompanyBackend.BusinessNotification.find();
setInterval(function() {
BusinessNotifications.reload();
}, 2000);
},
});
My Model:
CompanyBackend.BusinessNotification = DS.Model.extend({
notification: DS.attr('string'),
timeSeen: DS.attr('integer'),
active: DS.attr('boolean'),
type: DS.attr('string'),
});
My Serializer:
class BusinessNotificationSerializer < BaseSerializer
attributes :id, :business_id, :notification, :time_seen, :active, :type
end
My Route:
CompanyBackend.BusinessNotificationRoute = Em.Route.extend({
model: function() {
return CompanyBackend.BusinessNotification.find();
},
});
my router.js:
this.resource('business_notification', { path: '/' });
I have the controller and the route set up on the rails end, but those should be irrelevant or I would be getting some sort of rails error in the console.
Thanks for the help!
This problem happen because probally you are using the 1.0.0-beta.X versions. And your code is using the v0.14 or v0.13 api.
You have 2 choices:
1- You can update your code to use the 1.0.0-beta.3, this transition guide point the changes needed. Your code will become:
Ember.Application.initializer({
name: "reload-busisness-notifications",
initialize: function(container, application) {
var store = container.lookup('store:main')
var BusinessNotifications = store.find('businessNotification')
setInterval(function() {
BusinessNotifications.update();
}, 2000);
}
});
The initializer isn't madatory but I think it's a good idea because you have access to container, without use BusinessNotifications.__container__
2- You can get the v0.14 version here, and replace by your current.

Resources