air
air

Reputation: 6264

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.

Upvotes: 2

Views: 11029

Answers (4)

redShadow
redShadow

Reputation: 6777

Your PHP code is generating (in a very bad way..) some javascript code that will be executed by the script. Although it should work, this is definitely not the best way to do that - you should run the loop on the js-side, eventually passing values from your PHP script..

However:

The "undefined function" problem is given since you try to run the code before the function is created; using jQuery, to make some code executed only after everything is loaded, use:

$(document).ready(function(){
// Your code here..
})

or just

$(function(){
// Your code here..
})

As described here: http://api.jquery.com/ready/

For the for loop, you should generate some js like this:

<div id="meprocess"></div>
<script type="text/javascript">
for (i=1; i<=10; i++) {
jfun(i);
}
</script>

..maybe, generating the min/max values from the PHP script:

<?php
  $min = 1;
  $max = 10;
?>
<div id="meprocess"></div>
<script type="text/javascript">
for (i=<?php print $min; ?>; i<=<?php print $max; ?>; i++) {
jfun(i);
}
</script>

..that's more good practice than writing N function calls in order to loop..

Upvotes: 2

Kaken Bok
Kaken Bok

Reputation: 3395

Write the code before the PHP code. In that case the function jfun is known.

Upvotes: 0

Emanuele Minotto
Emanuele Minotto

Reputation: 415

First of all, ensure that your javascript function is above function uses.

Or try with <script>jfun("<?php echo $i;?>");</script>

Upvotes: 0

genesis
genesis

Reputation: 50976

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>

Upvotes: 4

Related Questions