How to display a php variable into html

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Make your code more concise with jQuery:

(1) Add this in your <head>:

<script src=""></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 ?>";

For your PHP, try the following two options:



<?php echo $postduration; ?>

Solution 2

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.

Solution 3

document.getElementById('yourElementId').innerHtml = duration;

Solution 4

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

 var duration = <? echo $postduration; ?>;
 var div = document.createElement("DIV");

Solution 5

No, wait, that’s wrong. First of all, the javascript above does not “retrieve” anything from anywhere (neither php, nor anyplace else). Php generates the javascript, meaning that if $postduration is 5, you will get var duration = 5;, and if postduration = “test”, you will get var duration = test; (which is invalid javascript and will crash/cause unwanted things to happen in your application.

Last, to get a variable from javascript into html, you either replace the content of some other object (with innerHTML or something like that), or you create a new element and insert that into the page.

Example here:

Solution 6

The code should be like that, use the "{$}" to put a variable in, and the "" are important.

echo "hi var is {$_var}";

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply