Dahker Furm Dahker Furm - 7 months ago 11
Javascript Question

How to pass a php variable from a php file to js file?

I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):

<html> Welcome <?php echo $login; ?> </html>

//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):

$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});

Answer

Easy way is storing the value from PHP in a input like this in you HTML:

<input id="login" type="hidden" val="<?= $login ?>">

Then, change the JS to something like:

$("#newMsgSend").click(function()//triggers script to send the message
    {
        $("#newMsgCnt").val(''); // clears the box when the user sends a message
        var username = document.getElementById("login").value;
        alert(username); 
    });