estier
estier

Reputation: 1

How do I get values from a PHP array to a Javascript Array?

So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. First I just echo'd the array like this:

PHP:

<?php
$exampleArray = ["212", "33", "7"]
?>

and JS:

<script> var jExampleArray = <? echo json_encode($exampleArray);?>;  </script>

And then I used jExampleArray in my bar chart code. Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page. I thought about using Ajax and what not but it just didn't work for me. I got it to alert me the array, but was not able to fill a Javascript array with it.

I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. Luckily I managed to at least understand the code I wrote/copied.

Edit: [] for a JS array not {}

Upvotes: 0

Views: 82

Answers (3)

ChristianG
ChristianG

Reputation: 458

If the PHP array is available at page load use:

<?php
$phpArray = array('data1' => 2, 'data2' => 3);
?>
<script>var arr = <?php echo json_encode($phpArray); ?>;</script>

To retrieve PHP array in JS after page load using ajax:

var arr = JSON.parse(responseArray);

Upvotes: 0

Jacob Mulquin
Jacob Mulquin

Reputation: 3608

Your syntax for creating the PHP array is incorrect.

Use the function json_encode to transform PHP arrays into Javascript arrays and objects.

<?php

$arr = ['hello', 'world', 'foo', 'bar'];
$obj = ['hello' => 'world', 'foo' => 'bar'];

echo 'var Array = ' . json_encode($arr) . PHP_EOL .
     'var Obj = ' . json_encode($obj, JSON_FORCE_OBJECT) . PHP_EOL;

Will result in the following:

var Array = ["hello","world","foo","bar"]
var Obj = {"hello":"world","foo":"bar"}

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33813

Some pseudo code to show how you might accomplish the stated goal

$data=array();
while( $rs=$db->fetch() ){
    $data[]=array(
        'field_1'   =>  $rs->field_1,
        'field_2'   =>  $rs->field_2,
        'field_3'   =>  $rs->field_3
    );
}

$json=json_encode( $data );


<script>
    <?php
        echo "var jExampleArray={$json};";
    ?>
    /* rest of barchart code */
</script>

Upvotes: 0

Related Questions