Home > Net >  JavaScript Random Message
JavaScript Random Message

Time:10-30

I need to create a random message when there is a successful match in my PHP code, but I am unsure how to accomplish this with JavaScript. In my code, the PHP pulls the username and password from a file and then checks to see if that username and password entered by the user matches. If so they gain access and the form disappears to show a message (that I am trying to figure out how to do). If not, then access is denied and the form stays for them to try again.

I have tried changing the code to onload, onclick, and by addEventListener, but nothing will display. I have also tried changing the HTML tag to element and p. Is this not possible to do? I didn't think the onclick would be good since the submit button is clicked either way but I tried it to see if I could get it to work anyway.

PHP

    //NO ERRORS AVAILABLE AND THE BUTTON HAS BEEN PUSHED
    if (!$error && isset($_POST['submit']))
    {
        echo '<div class = "output">
        <h1 class = "success">'.$msg.'</h1>
        <p id="welcomeDisplay" onload="newWelcome()"></p>
        <p id="welcomemsg"></p>
        </div>';
    }

JavaScript

var welcome = 
[
    "Success feels so good!",
    "You made it!",
    "You are worthy!",
    "Open Sesame",
    "Welcome to the dark side!",
    "Hola!",
    "So glad you are back!",
    "Hello, sunshine!",
    "Howdy, partner",
    "what's kickin', little chicken?",
    "Peek-a-boo!",
    "Ahoy, matey!",
    "Aloha!",
    "Bonjour!",
    "Hallo!",
    "Ciao!",
    "Konnichiwa!"
];

/*-----------------------------------------------------------------*/
function newWelcome()
{
    var randomNumber = Math.floor(Math.random() * (welcome.length));    
    document.getElementById('welcomemsg').innerHTML = welcome[randomNumber];
}

CodePudding user response:

If the php script is at root level you might try adding something like this to your scripts.js file but you might need to tweak it to account for no script name in the url or a path if it is in a sub-folder.

document.addEventListener('DOMContentLoaded',()=>{
    let arr=location.href.split('/');
    let page=arr.pop();
    let path=arr.pop();
    /*
        You might need to use the path variable too!
    */
    if( page=='index.php' ){
    
        const welcome=[
            "Success feels so good!",
            "You made it!",
            "You are worthy!",
            "Open Sesame",
            "Welcome to the dark side!",
            "Hola!",
            "So glad you are back!",
            "Hello, sunshine!",
            "Howdy, partner",
            "what's kickin', little chicken?",
            "Peek-a-boo!",
            "Ahoy, matey!",
            "Aloha!",
            "Bonjour!",
            "Hallo!",
            "Ciao!",
            "Konnichiwa!"
        ];
        let msg=welcome[Math.floor(Math.random() * (welcome.length))];
        document.getElementById('welcomemsg').innerHTML=msg
    }
})
  • Related