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