开发者

Running JavaScript in PHP file

开发者 https://www.devze.com 2023-03-11 17:51 出处:网络
I made a simple login using JavaScript, but record the username in a PHP session.It\'s a simple web chat, so I want when the chat page is loaded the user to be forced to pick an username, but after th

I made a simple login using JavaScript, but record the username in a PHP session.It's a simple web chat, so I want when the chat page is loaded the user to be forced to pick an username, but after that I want to store that info ina a PHP session and if the page is reloaded for some reason to do a check if $_SESSION['UserName'] is empty and if it's not to stop the script from executing again.I put my login JS in <body onload..> and the code looks like this:

<body onload = "showUser(), showChat(), <?php if ($_SESSION['UserName']==""){
{
  Login();
}?>">

I'm just learning now, so I gues I have some newb mistakes, like I'm almost sure that I'm not calling the Login() function right (it's JS function), but that's my strating point.Could anyone explain to me, how should I do the check properly and add the JS function in my PHP code?

P.S And I don't know if this really matter but if I remove the PHP code and leave liek this:

<body onload = "showUser(), showChat(),Login()">

My script is executed properly and I get everything that should be shown when the page is loaded, but when I add the PHP script and try to load the page I get blank page.I really wonder what's开发者_如何学C the reason for this too?


You cant call a js function from php. instead we have to print the js function as string in php so it will be executed as js along the html.

<body onload = "showUser(); showChat(); <?php if ($_SESSION['UserName']==""){ echo 'Login();'; }?>">

To Write efficient php code:

<body onload = "showUser(); showChat(); <?php echo (($_SESSION['UserName']=='')?'Login();':''); ?>">



You get blank page because of fatal error. which is occurred due to the javascript function you called in php (ERROR: Undefined function login() ).


You must echo the text Login(); from PHP - PHP does not execute Javascript, but you can use it to control which Javascript functions are called.

<body onload="showUser(), showChat(), <?php 
    if(isset(!$_SESSION['UserName']) || $_SESSION['UserName'] == ""){ 
        echo 'Login();';
     }?>">

You are effectively using PHP to create two different body tags - one for logged in users, and one for others.

Side note: it's good practice to check that an array item exists before attempting to access it: isset($_SESSION['UserName']) || $_SESSION['UserName'] checks first if $_SESSION['UserName'] has been set, then checks if it has been set to something other than an empty string.


You can simply call this as:

<?php 
    if($_SESSION['UserName'] == ""){ 
?>
<body onload="showUser(), showChat()">
<?php
    }
    else
    {
?>
<body onload="showUser(), showChat(), Login();">
<?php
    }
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号