TopoX TopoX - 1 year ago 69
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,".",","));


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) ?>";

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


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) ?>;


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


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.

$price = 2523525;

<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download