SOFuser123
SOFuser123

Reputation: 105

invocating same jquery script multiple times

How can i invoke a jquery script multiple times by using a php foreach loop.The jquery script draws a pie chart based on data present in the session for every iteration of the loop.

Upvotes: 0

Views: 121

Answers (4)

Jonathan
Jonathan

Reputation: 773

You can also adapt your javascript function to accept arrays as parameter.

If so you can via PHP set values of an array and then call the function only one time:

<script type="text/javascript">
<?php
    echo "var arrayPies = [";

    for($i=0; $i <= 10; $i++){
        echo ($i<10) ? "$i," : "$i";
    }

    echo "];\n";

    echo "callPieFunction(arrayPies);";
?>
</script>

The above code will output something like this:

var arrayPies = [0,1,2,3,4,5,6,7,8,9,10];
callPieFunction(arrayPies);

Upvotes: 0

Alex
Alex

Reputation: 1304

This would call jsFunction() 10 times with params from 0 to 10

<script type="text/javascript">
$(document).ready(function(){
<?php
    for($i=0; $i <= 10; $i++;){
        echo 'jsFunction(' + $i + ')';
    }
?>
});
</script>

Which is equivalent to simply writing (and will output this to page):

<script type="text/javascript">
    $(document).ready(function(){
        jsFunction(0);
        jsFunction(1);
        jsFunction(2);
        jsFunction(3);
        jsFunction(4);
        jsFunction(5);
        jsFunction(6);
        jsFunction(7);
        jsFunction(8);
        jsFunction(9);
    });
</script>

Upvotes: 0

DGS
DGS

Reputation: 6025

You can write a new script tag or jQuery function in the foreach loop

    echo '<script>';
    foreach(....){
        echo 'drawPieFunction();';
    }
    echo '</script>';

highly recommend against this though since it has next to no good uses

Upvotes: 0

fusio
fusio

Reputation: 3675

PHP is server side, JavaScript (jQuery) is client side. You cannot use PHP to invoke a JavaScript function.

Upvotes: 2

Related Questions