Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a php variable into html

Tags:

html

php

I just want to know how can I display a javascript variable into html?

Below is my php code:

var duration = <? echo $postduration; ?>;

(The variable above uses php to retrieve a php variable)

Thank you

like image 845
BruceyBandit Avatar asked Jan 06 '12 23:01

BruceyBandit


4 Answers

Make your code more concise with jQuery:

(1) Add this in your <head>:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

(2) Create an element where you want the variable to be displayed, and give it an ID, e.g.:

<span id="printHere"></span>

(3) Add this in your JavaScript:

var duration="<?php echo $postduration ?>";
$('#printHere').html(duration);

For your PHP, try the following two options:

<?=$postduration?>

or...

<?php echo $postduration; ?>
like image 174
calebds Avatar answered Nov 03 '22 12:11

calebds


Why don't use just display the php variable directly into the html?

Lets just say $postduration echos "some." Here is the javascript code to echo "some":

Here is <script>document.write(duration)</script> text.

Here will be the output:

Here is some text.
like image 34
blake305 Avatar answered Nov 03 '22 12:11

blake305


document.getElementById('yourElementId').innerHtml = duration;
like image 34
Atonewell Avatar answered Nov 03 '22 10:11

Atonewell


Here's a way to add a DIV to a page with the content of the DIV being the value of your PHP var:

 <script>
 var duration = <? echo $postduration; ?>;
 var div = document.createElement("DIV");
 div.appendChild(document.createTextNode(duration));
 document.body.appendChild(div);
 </script>
like image 26
mrk Avatar answered Nov 03 '22 12:11

mrk