Hi I'm trying to execute an HTTP DELETE
request using the sweet alert 2
library on Rails 6.1.3.1
! When I try something like this it works perfectly see my other question about this issue:
<button script='
Swal.fire(
"Good job!",
"You clicked the button!",
"success"
)
location.pathname = "<%= home_about_path %>"; //redirect to About Page
'>TEST</button>
But that would only work with GET
request. Therefore it has been suggested that to achieve another type of request (i.e. DELETE
), I would have to use AJAX
. So, I found out that you can use Rails.ajax(...)
to execute asynchronous JavaScript. But when I add the following code, I get the error: friends:22 Uncaught (in promise) ReferenceError: Rails is not defined
.
//dir: project-name/app/views/friends/index.html.erb
Swal.fire(
"Good job!",
"You clicked the button!",
"success"
)
Rails.ajax({
type: "GET",
url: "<%= home_about_path %>",
success: function(response){ alert("succes Go to About Page") },
error: function(response){ alert("error :" + response) }
});
Therefore I tested Rails.ajax(..)
inside project-name/app/javascript/packs/application.js
where the declaration of the Rails
is made! Of course the following code will result in an infinite loop. But this was done only for testing purposes! And it works fine. The page redirects to about page again and again and again.
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
Rails.start()
Turbolinks.start()
ActiveStorage.start()
Rails.ajax({
type: 'GET',
url: '/home/about',
success: function(response){ location.pathname = "/home/about" },
error: function(response){ alert('error delete' + response) }
});
So my question is why the command Rails.ajax()
will work where it is declared, but not on a specific page/controller? How to tell rails to declare the Rails
var to the whole system?
SOLUTION by @Joel_Blum:
application.js
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
Rails.start()
Turbolinks.start()
ActiveStorage.start()
window.Rails = Rails;
index.html.erb:
Swal.fire(
"Good job!",
"You clicked the button!",
"success"
)
var redirect = '<%= friends_path %>';
redirect += '/<%= friend.id %>';
Rails.ajax({
type: 'DELETE',
url: redirect,
success: function(response){
//Friend has been deleted!
},
error: function(response){
//Error with Ajax
alert('error delete' + response)
}
});