Search code examples
javascriptphpsweetalertsweetalert2

Passing PHP variabe in Sweet alert 2


I want to display the PHP variable in sweet alert but unable to find the solution, I went through the documentations of sweet alert 2 but couldn't find anything. Can anyone help me?

here's my code

$name = "xyz";

//sweetalert code
echo "<script>";
echo 'setTimeout(function () { swal("Greetings $name!","Thank you for adding your business details.<br>Our admin team will review the same and will publish shortly..!","success");';
echo '}, 100);</script>';

Solution

  • Just need to switch the quotes:

    echo "setTimeout(function () { swal('Greetings $name!','Thank you for adding your business details.<br>Our admin team will review the same and will publish shortly..!','success');'";
    

    Or, another option, concatenate variables within string:

    echo 'setTimeout(function () { swal("Greetings ' . $name . '!","Thank you for adding your business details.<br>Our admin team will review the same and will publish shortly..!","success");';
    

    When you include a variable inside echo, you need to use "

    Know difference between " and ' another SO Answer