0

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.

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

But you can print out JavaScript with PHP and the function will be invoked
Yes, of course. It does not make any sense, but you could do that.
0

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

Comments

0

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>

2 Comments

It'll be better if you put the <script> tags outside the loop
this would write ten times the script tag, it is better to let the script tag outside the loop...
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.