Rossygnol
Rossygnol

Reputation: 83

increment php variable used in javascript

I wanted to display a graph in javascript using data from php. My code is:

<?php $i = 20; ?>
while (data.length < totalPoints) {
    array_js.push(<?php echo json_encode($array_php[++$i][1]);?>);
}

The problem is that even though $i is declared before the while loop, it gets back to 20 all the time, so the data pushed in array_js is always $array_php[21][1].

Edit: here is more code, (not same variable name...)

startConn(); //connect to database

$query = "SELECT * FROM Reading";
$data = getAllDatas($query);
?>

<script type="text/javascript">
    $(function() {

    var data = [], totalPoints = 300;

        function getRandomData() {

            <?php $i = 20; ?>
            while (data.length < totalPoints) {
                data.push(<?php echo json_encode($data[--$i][1]);?>);
                //data.push(<?php echo ++$i;?>);
            }
        } // END getRandomData()

Upvotes: 2

Views: 944

Answers (2)

Nadimul De Cj
Nadimul De Cj

Reputation: 484

You have a misunderstanding on how server side and client side code work.
I think this may help you

$(function() {
    var data = [], totalPoints = 3;
    var i = <?php $i = 1;echo $i; ?>;
    var j = parseInt(i);
    var arr = <?php echo json_encode($data); ?>;

    function getRandomData() {
        while (data.length < totalPoints) {
            data.push(arr[j][1]);
            j++;
        }
        return data;
    }
    var data1 = getRandomData();
    console.log(data1);
});

Upvotes: 1

Lee Balino
Lee Balino

Reputation: 490

Try this one. You can pass the value of the php variable using echo while declaring another variable on the java script.

<?php $i = 20; ?>
var i = <?php echo $i;?>;
while (data.length < totalPoints) {
    array_js.push(<?php echo json_encode($array_php[++i][1]);?>);
}

Upvotes: 0

Related Questions