TopoX TopoX - 9 months ago 36
HTML Question

how to display output from PHP into HTML

basically what I've been trying to do is with PHP get a integer from MySQL after that is done, using JavaScript get the integer that PHP has and display it on HTML

<?php include('ConnectionCode.php');

$conn = mysqli_connect($svr, $usr, $pwd, $db) or die("Could not connect " . mysql_error());

$sql = "SELECT RetailPrice FROM WebHosting_PricingCOP WHERE id='32402' LIMIT 1";
$result = mysqli_query($conn, $sql);
$price = mysqli_fetch_array($result);

echo json_encode(number_format($price['RetailPrice'],0,".",","));

mysqli_close($conn)
?>


the code above will connect to the Database and get the value 59,347
now I'm trying to move this single value from PHP to Javascript in order to display it on HTML

<script type="text/javascript">
var PriceValue = "<?php echo json_encode($price) ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>


I have gone through many discussions and options here and there and still cant figure out to make it work, when i try to run the html it doesn't display anything

I would greatly appreciate your input

Answer Source

Update:

You may also have a problem with using json_encode inside of "" quotes.

var PriceValue = "<?php echo json_encode($price) ?>";

Instead, use:

var PriceValue = <?php echo json_encode($price) ?>;

or

var PriceValue = <?php echo $price ?>; // if $price is not an object

Note:

To debug this, check the generated HTML source to see what JavaScript you are actually generating.


$price needs to be in the same scope when you try to generate JS.

http://phpfiddle.org/main/code/aeav-gb1w

<?php
$price = 2523525;
?>

<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>

However, it is going to be preferable for you to use your PHP file as an API endpoint instead of mixing your PHP and JavaScript together.