Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  198] [ 1]  / answers: 1 / hits: 86475  / 14 Years ago, tue, december 28, 2010, 12:00:00

Why is this not working?



<?php 

mysqli_select_db($connect,dev);
$response = Select response from revbut where session='$u';
$rquery = mysqli_query($connect,$response);

$responseanswer = mysqli_fetch_array($rquery);
$re = $responseanswer['response'];
?>

<script type=text/javascript>
<?php echo $re; ?>
</script>


$re inside JavaScript is not getting echoed. But if I place it inside the above PHP function, it is getting echoed.



EDIT - BUT THEN WHY IS THIS NOT WORKING?



if(<?php echo $re; ?>){
document.getElementById('hide').style.display = none;
}


if I PLACE the hide function outside the if - it is working.


More From » php

 Answers
8

It get's echoed, but you won't see anything on your page as the text will be written within the Javascript-tag which is not displayed by the browser. Look at your page source to verify that the text is really there.



EDIT



Try



if(<?php echo json_encode($re); ?>){
document.getElementById('hide').style.display = none;
}


This will ensure that your PHP string will be converted into the appropriate Javascript type - in case of strings it'll ensure that the string is enclosed in and is escaped properly.



EDIT again



When you do the following



<script type=text/javascript> 
if(<?php echo $re; ?>){
document.getElementById('hide').style.display = none; }
</script>


this is what is written to the HTML page (that's then interpreted by the browser)



<script type=text/javascript> 
if(whatever is in the $re vairable){
document.getElementById('hide').style.display = none; }
</script>


But this is not even valid Javascript. What you want is



<script type=text/javascript> 
if(whatever is in the $re vairable){
document.getElementById('hide').style.display = none; }
</script>


Note the which ensures that the whole thing is valid Javascript and that the contents of $re will be interpreted as an Javascript string by the Browser's Javascript engine. The call to json_encode() does exactly this - it transforms PHP variables into the appropriate Javascript variables.


[#94469] Friday, December 24, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamryn

Total Points: 645
Total Questions: 100
Total Answers: 118

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;