Sweet alert 2 in Ruby on Rails 7

rutikkpatel

Rutvik Patel

Posted on February 1, 2023

Sweet alert 2 in Ruby on Rails 7

Sweet alert 2 in Ruby on Rails 7

Traditional alert boxes are looking so boring. We do not apply styling to them as well. There are a plethora of ways to change the styling of this. So in this article, we are going to talk about one of the best JS libraries, “Sweet Alert 2.”

Sweet Alert with Rails 7 Created By [Rutik Patel](https://medium.com/@rutikkpatel)

Table of content

  1. What is Sweet Alert 2?

  2. Integration of Sweet Alert with Ruby on Rails

  3. Sweet Alert 2 as an alert box

  4. Sweet Alert 2 with the destroy button

  5. AJAX call with Sweet Alert 2

  6. References

Let’s start with sweet alert,


1. What is Sweet Alert 2?

Sweet Alert is a JavaScript library that is used to make an alert box and toast messages more stylish, elegant, and appealing, and it is a piece of cake to design that.

Sweet Alert 2 Logo by [https://sweetalert2.github.io/](https://sweetalert2.github.io/)

2. Integration of Sweet Alert with Ruby on Rails

We are going to use Rails 7.0.4 and Ruby 3.1.0.

Assume we have a simple crud rails application that was either scaffolded or manually created.

To use sweetalert, we are going to use Rails 7’s new importmap feature.
So let’s pin “Sweet Alert” using importmap.

bin/importmap pin sweetalert2
Enter fullscreen mode Exit fullscreen mode

Now we need to import this into the application.js. So, Add the following lines to the application.js

import Swal from 'sweetalert2';
window.Swal = Swal;
Enter fullscreen mode Exit fullscreen mode

Sweetalert has now been configured. Now you can use SweetAlert.

3. Sweet Alert 2 as an alert box

We can modify the default alert box and add “Sweet Alert” instead of that.

<button onclick= "defaultAlertBtn()"> Default Alert </button>
<button onclick= "sweetAlertBtn()"> Sweet Alert </button>
Enter fullscreen mode Exit fullscreen mode

Now add the script,

<script>
  function defaultAlertBtn() {
    alert("Button has been clicked")
  }
  function sweetAlertBtn() {
    Swal.fire({
      icon: 'success',
      title: 'Button has been clicked',
    })
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Screenshots :

Default Alert Box

Sweet Alert Alert Box

4. Sweet Alert 2 with the destroy button

We need to get confirmation from the user before deleting any data. So for that, we need to write some Javascript code.

Create the delete_confirmation_dialog.js file under the javascript folder. and Add the following code to it. app/javascript/delete_confirmation_dialog.js

window.addEventListener(('turbo:load'), () => {
  document.addEventListener('submit', (event) => {
    if (event.target && event.target.className === 'delete-alertbox') {
      event.preventDefault()
      Swal.fire({
          title: 'Are you sure?',
          text: "You won't be able to revert this!",
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          confirmButtonText: 'Yes, delete it!'
      })
        .then((result) => {
          if (result.isConfirmed) {
            document.querySelector('.delete-alertbox').submit()
          }
        })
        .catch(event.preventDefault())
    }
  })
})
Enter fullscreen mode Exit fullscreen mode

Then Include this file in application.html.erb. As a result, we can use that JavaScript code on any page of the application.

<%= javascript_include_tag "delete_confirmation_dialog" %>
Enter fullscreen mode Exit fullscreen mode

Finally, modify your destroy/delete button.

<%= button_to "Delete", some_path, method: :delete, form_class: 'delete-alertbox'%>
Enter fullscreen mode Exit fullscreen mode

Screenshot:

Delete Confirmation Dialog using Sweet Alert

5. AJAX call with Sweet Alert 2

You can also use this sweet alert in AJAX calls also.

$.ajax({
  url: "/some_path",
  type: "post",
  data: { book_id: book.id },
  success: function (data) {
    Swal.fire({
      icon: 'success',
      title: 'AJAX call occurred successfully.',
      timer: 3000
    })
  },
  error: function (data) { },
});
Enter fullscreen mode Exit fullscreen mode

Screenshot :

6. References

My Github Repository : https://github.com/rutikkpatel/Sweet-Alert-Rails

SweetAlert Github Repository : https://github.com/sweetalert2/sweetalert2

SweetAlert Website : https://sweetalert2.github.io/

💖 💪 🙅 🚩
rutikkpatel
Rutvik Patel

Posted on February 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Sweet alert 2 in Ruby on Rails 7
rails Sweet alert 2 in Ruby on Rails 7

February 1, 2023