Search code examples
javascripthtmlruby-on-railserbsweetalert2

How to execute a rails command with sweet alert 2?


I have the following sweet alert 2 message:

<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        Swal.fire("Saved!", "", "success");
      } else if (result.isDenied) {
        Swal.fire("Changes are not saved!", "", "info");
      }
    });
'>SHOW SWEET ALERT</button>

The design looks to work okay, but the issue is that I cannot execute an .erb command instead of showing another sweet alert message!

So for example if I change the above code to the following it will mess everything up and I don't know what is causing this!:

<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        <%= link_to "Home Page", root_path, class:"navbar-brand" %>
      } else if (result.isDenied) {
        <%= link_to "About Page", home_about_path, class:"nav-link" %>
      }
    });
'>SHOW SWEET ALERT</button>

CODE SNIPPET 2 WILL GIVE THE FOLLOWING ERROR: Uncaught SyntaxError: Unexpected token '<'

Image example of first snippet: image 1

Image example of second snippet: image 2


Solution

  • Actually that is the expected behaviour.

    As you can see in the second screenshot, the ERB parser has generated the correct anchor tags inside your JavaScript code causing the SyntaxError. (You can't have HTML in JavaScript! Unless they are around string quote marks of course.)

    What you want to do is this instead:

    <button onclick='
        Swal.fire({
          title: "Select a page you want to be redirected:",
          showDenyButton: true,
          showCancelButton: true,
          confirmButtonText: "Home",
          denyButtonText: "About",
        }).then((result) => {
          /* Read more about isConfirmed, isDenied below */
          if (result.isConfirmed) {        
            location.pathname = "<%= root_path %>"
          } else if (result.isDenied) {
            location.pathname = "<%= home_about_path %>"
          }
        });
    '>SHOW SWEET ALERT</button>
    

    "location.pathname = x" will direct you to a relative path.

    The server's ERB parser will replace root_path and home_about_path variables with the paths you're looking for.