1

Here's what I got

$x=$ris;
while ($x<$rie){
     array_push($array, pg_fetch_result($result,$x,0));
     $x=$x+1;
}

So I'm just pushing lot's of values from a column to $array. I want to transmit the data in this array to a js array. So here's what's happening:

  <script>
  var temp = <?php echo json_encode($rie-$ris); ?>;
  var temp2=0;
  var jarray = [];
  while (temp2<temp)
  {
       jarray.push(<?php echo json_encode($array[temp2]); ?>);
       temp2++;
  }
  console.log(jarray)
  </script>

Whenever I try to print anything out, jarray has nothing in it, which leads me to think that this

       jarray.push(<?php echo json_encode($array[temp2]); ?>);

line is messed up. It's probably because I'm trying to reference a js variable in a php echo. The problem is I'm trying to make a while loop to just copy the array over, but in js, I'm incrementing a js var, so how can I possibly do this?

5
  • Why not first printing $array to javascript with json_encode, then not to use any php ? Commented Jan 20, 2016 at 19:49
  • In my opinion, you are better off sending the whole thing as a string to Javascript, and split it there. What you're doing is creating an object in one place, then recreating the exact same object using the same method elsewhere. Since you have to do that second step anyway, why bother the first time? Commented Jan 20, 2016 at 19:49
  • @ardabeyazoglu, So you mean during the while loop where I'm array_pushing? If so, how can I use json_encode if I can't set a js var value to it? Commented Jan 20, 2016 at 19:54
  • 1
    @john No. I meant use sth like var myArray = <?php json_encode($array) ?> before while. Then use myArray inside the while loop like myArray[temp2]``; Commented Jan 20, 2016 at 19:57
  • 1
    Your issue with jarray.push(<?php echo json_encode($array[temp2]); ?>); is basic php/JavaScript 101. Php is parsed server side before page load. JavaScript is parsed client side after page load. So when the JavaScript is running, the php is already parsed, so it won't change/accept your js values. Commented Jan 20, 2016 at 20:00

1 Answer 1

1

Try my code. First json_encode your php array and then JSON.parse in js after that while loop.

<script>
  var temp = <?php echo json_encode($rie-$ris); ?>;
  var temp2=0;
  var jarray = [];
  var arr = '<?php echo json_encode($array); ?>';
  var arr_p = JSON.parse(arr);
  while (temp2<temp)
  {
       jarray.push(arr_p[temp2]);
       temp2++;
  }
  console.log(jarray)
</script>
Sign up to request clarification or add additional context in comments.

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.