Skip to content
Advertisement

Can you call JavaScript function from PHP loop?

I am wounding if I can do this, as I am trying this from last 2 days but no success.

I want to run JavaScript function from PHP

PHP example

<div id="meprocess"></div>
<?php
for($i=1;$i<=10;$i++)
{
?>
<script>
jfun(<?php echo $i;?>);
</script>
<?php
}
?>

JavaScript

<script type="text/javascript">

function jfun(n)
{
html="Loop is on" + n;
$("<div>"+ html +"</div>").appendTo("div#meprocess");   
}
</script>

I am trying to generate a page which print loop number one by one.

But I got error jfun is not defined.

What I can understand my JavaScript function is not ready at the time of PHP execution. Is there any way round, like running the PHP loop when DOM/Page is ready so that the JavaScript function will be ready that time, or any other way round.

Advertisement

Answer

You have to define that function before calling it

http://sandbox.phpcode.eu/g/15b02.php

<div id="meprocess"></div>
<script type="text/javascript">

function jfun(n)
{
html="Loop is on" + n;
$("<div>"+ html +"</div>").appendTo("div#meprocess");   
}
<?php
for($i=1;$i<=10;$i++)
{
?>
jfun(<?php echo $i;?>);
<?php
}
?>
</script>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement