How to loop through data from php in javascript?

995

I want to ask how to the repeat a region in javascript? The data are dynamic and I want to find all items through phpdo...while loop:

<script type="text/javascript">

    window.onload = function () {
    <?php do{ ?>
        var chart<?php echo $row_RecAllAnswers['q_id']; ?> = new CanvasJS.Chart("<?php echo $row_RecAllAnswers['q_id']; ?>", {
            theme: "theme2",//theme1
            title:{
                text: "No. " + "<?php echo $row_RecAllAnswers['q_id']; ?>"              
            },
            animationEnabled: true,   // change to true
            data: [              
            {
                // Change type to "bar", "splineArea", "area", "spline", "pie",etc.
                type: "column",
                dataPoints: [
                    { label: "A" ,  y: <?php echo $row_RecAllAnswers['A']; ?>  },
                    { label: "B", y: <?php echo $row_RecAllAnswers['B']; ?>  },
                    { label: "C", y: <?php echo $row_RecAllAnswers['C']; ?>  },
                    { label: "D",  y: <?php echo $row_RecAllAnswers['D']; ?>  }
                ]
            }
            ]
        });
        chart<?php echo $row_RecAllAnswers['q_id']; ?>.render();
        chart<?php echo $row_RecAllAnswers['q_id']; ?> = {};
        window.alert(<?php echo $row_RecAllAnswers['q_id']; ?>);
        <?php } while ($row_RecAllAnswers = mysql_fetch_assoc($RecAllAnswers));  ?> 
    }

</script>
782

Answer

Solution:

  1. Use json_encode to convert your mysql query result to JSON.
  2. Write the JSON to your HTML.
  3. In Javascript use a foreach on the JSON array to iterate.
288

Answer

Solution:

json encode that php array into a javascript variable and then loop through that variable. In twig I do it like this:

var objectName = {{ phpVariable|json_encode|raw }};

so I think this should work find in PHP (did not test it):

var objectName = <?php echo json_encode($phpVariable); ?>;

Then the javascript variable 'objectName' will contain your data and now you can use regular javascript to loop through the data. You can also use underscore as it is easier.

_.each(objectName, function(item, key){
//do stuff here
});

People are also looking for solutions to the problem: php - Correct api access url in codeigniter

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.