kooliebwoy
kooliebwoy

Reputation: 353

How to reference .js file from php function?

It is not recognizing the swal from SweetAlert because it is not finding the js file. I cannot do it the conventional way in the header for html for certain reasons. Is there any way to get this to work?

This code gives the error sweetalert2.min.js:1Uncaught TypeError: Cannot read property 'appendChild' of null

I have tried moving the script for the js all over the place but still doesn't work. Any help would be great. Thanks.

function alert_swal($title, $message, $type)
{
    //External CSS and JS
    echo '<link href="https://cdn.jsdelivr.net/sweetalert2/4.0.5/sweetalert2.min.css" rel="stylesheet">';
    echo '<script src="https://cdn.jsdelivr.net/sweetalert2/4.0.10/sweetalert2.min.js"></script>';

    echo '<script type="text/javascript">';
    echo 'swal(\'' . $title . '\',\'' . $message . '\',\'' . $type . '\');';
    echo '</script>';
}

Upvotes: 0

Views: 76

Answers (2)

Jahid Mahmud
Jahid Mahmud

Reputation: 1136

You should write this

function alert_swal($title, $message, $type)
{
    //External CSS and JS
    echo '<body>';
echo '<link href="https://cdn.jsdelivr.net/sweetalert2/4.0.5/sweetalert2.min.css" rel="stylesheet"/>';
echo '<script src="https://cdn.jsdelivr.net/sweetalert2/4.0.10/sweetalert2.min.js"></script>';
echo '<script type="text/javascript">';
echo 'swal(\'' . $title . '\',\'' . $message . '\',\'' . $type . '\');';
echo '</script>';
echo '</body>';
}

Upvotes: 1

mujuonly
mujuonly

Reputation: 11861

echo '<body>';
echo '<link href="https://cdn.jsdelivr.net/sweetalert2/4.0.5/sweetalert2.min.css" rel="stylesheet"/>';
echo '<script src="https://cdn.jsdelivr.net/sweetalert2/4.0.10/sweetalert2.min.js"></script>';
echo '<script type="text/javascript">';
echo 'swal(\'' . $title . '\',\'' . $message . '\',\'' . $type . '\');';
echo '</script>';
echo '</body>';

Upvotes: 1

Related Questions