简体   繁体   中英

Include defined PHP variable in Javascript

I am not too familiar with Javascript so I was hoping I could get a little advice on how to include a PHP variable within javascript.

I have written a PHP code to set a variable waiting time for a hyperlink depending on server load.

A snippet of the PHP code is:

// set wait level
if($count_user_online <= "99") {
    $wait_level="0";
}
else if($count_user_online >= "100" && $count_user_online < "199") {
    $wait_level="60";
}
else if($count_user_online >= "200" && $count_user_online < "299") {
    $wait_level="120";
}
else if($count_user_online >= "300" && $count_user_online < "399") {
    $wait_level="180";
}
else if($count_user_online >= "400" && $count_user_online < "499") {
    $wait_level="240";
}
else if($count_user_online >= "500") {
    $wait_level="300";
}

I am trying to echo $wait_level within the Javascript. I have done it the HTML method below, but obviously this isn't correct. Can anybody suggest a functional approach?

<html>
<head>
<script type="text/javascript">
window.onload=function() {
document.getElementById('redirect').style.display = 'none';
function countdown() {
if ( typeof countdown.counter == 'undefined' ) {
   countdown.counter = <?php echo $wait_level ?>; // seconds
   }
if(countdown.counter >= 0) {
   document.getElementById('count').innerHTML = countdown.counter--;
   setTimeout(countdown, 1000);
   }
else {
   document.getElementById('redirect').style.display = '';
   }
}
countdown();
};
</script>

</head>
<body>
<h2>You can can access the link in <span id="count"></span> seconds <a id="redirect" href="http://google.com/">Google</a></h2>
</body>
</html>

I am aware the javascript I am using will allow you to easily view the hyperlink by viewing the source, but this isn't the final javascript code I will be using so there is no need to worry about that.

The script will only be used for 1 day on a private server so does not need to be clean, just functional.

Any help is really very much appreciated!

The way I'd go about getting PHP to JavaScript would be using Ajax

Ajax you'll be able to load data from your server by using a HTTP Post request, the good thing about using Ajax is that you can send parameters with the HTTP request. Eg If you wanted to send a parameter which would be used for a DB query. Then you'd be able to do so and you'd be able to return the data from that DB query.

I'm not saying it's bad practise to use PHP inside JavaScript because it's perfectly acceptable, but it can be very risky - you're generating parts of the JS on-the-fly, which means you have to generate VALID JS code, or the whole code block will be killed by a syntax error.

eg

<script type="text/javascript">
   var lastName = '<?php echo $lastName ?>';
</script>

and $lastName happens to be O'Neil, you've now introduced a syntax error, because the generated code will be:

var lastName = 'O'Neil';
                --- string with contents O
                   --- unknown/undefined variable Neil
                     -- string followed by variable, but no operator present.
                        --- start of a new unterminated string containing a ';'

So if you was going to carry on with inserting raw PHP-based data into a JS variable, you basically MUST use json_encode(), which guarantees that the generated JS data is syntactically valid JS code

My method getting PHP data

Server side - Test1.php

<?php

if (isset($_POST['usersOnline']))
{


$count_user_online = $_POST['usersOnline'];

switch ($count_user_online) {
    case  ($count_user_online <= "99"):
            $wait_level = "0";
        break;

    case  ($count_user_online >= "100" && $count_user_online < "199"):
            $wait_level = "1";
        break;

    case  ($count_user_online >= "200" && $count_user_online < "299"):
            $wait_level = "2";
        break;
}

echo $wait_level;

}

?>

HTML Side - Test.php

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">     </script>
<script>

$(document).ready(function() {
    sendUserCount("200");
    document.getElementById('redirect').style.display = 'none';
});

function countdown(count) {
     if ( typeof countdown.counter == 'undefined' ) {
        countdown.counter = count; // seconds
     }

     if(countdown.counter >= 0) {
        document.getElementById('count').innerHTML = countdown.counter--;
        setTimeout(countdown, 1000);
     }
     else {
        document.getElementById('redirect').style.display = '';
     }
  }

  function sendUserCount(userCount)
  {
     var url = document.location.href;
     $.post("test1.php",
     {
        usersOnline: userCount
     })

     .success(function (data)
     {
        console.log(data);
        countdown(data);
     });
   }

</script>

</head>
<body>
  <h2>You can can access the link in <span id="count"></span> seconds <a id="redirect" href="http://google.com/">Google</a></h2>
</body>
</html>

I am not sure if there is a better way of doing it, but I have managed to make it work with the following code:

<html>
<head>

<div id="dom-target" style="visibility: hidden">
<?php 
    echo htmlspecialchars($wait_level); 
?>
</div>

<script type="text/javascript">
var div = document.getElementById("dom-target");
var myData = div.textContent;
window.onload=function() {
document.getElementById('redirect').style.display = 'none';
function countdown() {
if ( typeof countdown.counter == 'undefined' ) {
   countdown.counter = myData; // seconds
   }
if(countdown.counter >= 0) {
   document.getElementById('count').innerHTML = countdown.counter--;
   setTimeout(countdown, 1000);
   }
else {
   document.getElementById('redirect').style.display = '';
   }
}
countdown();
};
</script>

</head>
<body>
<h2>You can can access the link in <span id="count"></span> seconds <a id="redirect" href="http://google.com/">Google</a></h2>
</body>
</html>

You can create parameterized functions in javascript like this

 function countdown(counter) {
    if ( counter != 'undefined' and counter != -1  ) 
    {
       if(counter >= 0) {
        document.getElementById('count').innerHTML = counter--;
        setTimeout(countdown(counter), 500);
       }
    else {
       document.getElementById('redirect').style.display = '';
       }
    }
}
    countdown(<?php echo $wait_level ?>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM