Search code examples
javascriptphptoastmaterialize

Materializecss Toasts with PHP


So I'm making this web control panel but I'm not good with JS. I'm using MaterializeCSS + HTML + PHP for the DB login and so on.

I would like to have the following simple functionality but for some reason I'm failing.

I'd like to fill in the username and password in my form and press Log in. Since I'm not sure how Toasts work, I suppose once I switch the page the Toast actually disappears so maybe it's better to display the toast in the new Account page that opens instead of the Login page itself. I tried both but it doesn't appear.

Code to show Toast:

echo "<script> Materialize.toast('Login successful!', 3000, 'rounded')   </script>";

I found a topic somewhere in Russian saying this has a problem with DOM and used its solution without success again.

Note: I already use other JS-dependent components such as Modals and Tooltips.

Console error: Uncaught ReferenceError: Materialize is not defined


Solution

  • I had 2 problems. Most importantly, I was testing the code in an IF that wasn't even executed. Stupid me. Secondly, I wasn't using onDocumentReady - $(function(){});

    The document referrer is just to check which page sent me there but here's my working code to create a MaterializeCSS Toast from PHP:

    echo "
    <script>
    $(function(){
       if (document.referrer == 'http://yourdomain/index.php?p=Login'){
        Materialize.toast('Login successful', 2200, 'rounded')
    }
    });  
    </script>";