Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Megatech's avatar

SweetAlert not working

Please i need help, i don't know why sweetAlert is not working despite doing everything correctly, (if i write my php code in the same place with the form it works fine, but i can't write my code that way). Here is my code,

<?php 
   
   session_start();
   include("database/userController.php");
  

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="assets/package/dist/sweetalert2.all.js"></script>
    <link rel="stylesheet" href="assets/package/dist/sweetalert2.min.css">
</head>
<body>
    <div>
        <form action="" method="post">
            <button type="submit" name="int_trans">submit</button>
        </form>
    </div>
</body>
</html>

my php file

<?php 

if(isset($_POST['int_trans'])) {
  
    echo "<script>
      Swal.fire(
          'Good job!',
          'You clicked the button!',
          'success'
        )
      </script>";
}
?>

Just a simple code that refused to run, the error i get in my console is

Uncaught ReferenceError: Swal is not defined

0 likes
8 replies
Sinnbeck's avatar

Always prefix asset urls with /

<script src="/assets/package/dist/sweetalert2.all.js"></script> 
Megatech's avatar

@Sinnbeck this will throw an error. Assets is a folder i created and it is in my localhost root folder, then the form is in my localhost root folder not inside any folder

Megatech's avatar

@Sinnbeck please note that this is a normal php, html, css and javascript project, not a framework (not laravel). so i created my folders and place my scripts in them.

my root folder is http://localhost/project

Sinnbeck's avatar

@Megatech if your files are in any folders but the root folder it will break without my suggested fix (unless you change thar url on all pages :))

Anyways. Just a suggestion to spare yourself some headaches

Sinnbeck's avatar

Is the php included in that other page with the script somehow? Or how is that script loaded before this Swal.fire? Be aware that it needs to be on the same page

Megatech's avatar

@Sinnbeck Do you mean in my form page? yes i included it like this

<?php 
   
   session_start();
   include("database/userController.php");
  

?>
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Megatech ok first off. It is echoing things so that should inside your body tag on the page. Currently you are outputting it before html is even being rendered. Secondly, perhaps you should have some function you could call?

Please or to participate in this conversation.