3

How can I change the value of a js variable in a PHP foreach loop?

The js needs to be external.

This is a piece of the index.php here I want to get the output $prozent in the javascript, I don't know how to get a PHP variable to execute a js every time in a loop, the js is a chart. I get the chart in the loop in the echo'<div class="chart-wrapper"> with a this chart js.

<?php
                $sql = //SQL query
                $res = mysql_query($sql);
                $i = 0;
                $survey = array();
                 while ($row = mysql_fetch_assoc($res)) {
                    $survey[$i]['label'] = $row['Label'];
                    $i++;
                }

                    foreach ($survey as $survey) {    
                    echo '<div class="col-md-4">';
                    echo '<div class="front face">';                

            echo "<h3> ".$survey['label']."<br>";
            $sql = //SQL Query
            $res = mysql_query($sql) ;
            $sql = //SQL Query
                $resSum = mysql_query($sql) ;
            while ($row = mysql_fetch_array($resSum)) {
                $survey['ausgabe'] = $row['sum(a.answer)'];
                 }


                $anzahlreihen = mysql_num_rows($res);
                if ($anzahlreihen > 0) {    
                $prozent = $anzahlreihen * $survey['ausgabe'];
                   //bunch of ifelse statements
              //This is the variable i want to get in the js    
            echo (round( $prozent, 2));
                    echo '</font>';
                }
                }
            echo '</div>';
            echo '<div class="back face center">';
            echo'<div class="chart-wrapper">
        }

1 Answer 1

1

There are two ways PHP and Javascript can interact.

Use AJAX to request a PHP script which returns JSON or have PHP output the following example HTML;

<script type="text/javascript">
var variable = value;
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

You could also imagine a php handler returning a full js file as output. And in your AJAX alternativ, it's worth notinh you don't necessarily return a JSON formatted answer from your php, it could be anything, although JSON(P) is generally the best fit...
Indeed, rethink the structure of your logic.
@doveyg Could it be possible if i take the variables multiple times out of the innerhtml with js?
That would work, yes. Do you need to display it though?
It would be nice, im seaching, but my js dont start with a function, and i dont know whitch function i need to call for execute the whole thing :(
|

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.