Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array loading into javascript

so I am a total php/javascript noob.

I'm trying load a full php array into a javascript array. I wrote this for Javascript:

    var names = new Array();
for(var i = 0; i < 48; i++) {
    names[i] = "<?php echo giveJS() ?>";
}

And this for php

static $counter = 0;

function giveJS() {
    global $names;
    global $counter;
    $counter++;
    return $names[$counter]; 
}

I already checked if the php array is correctly filled with data. When I write a output line in javascript, like

document.write(names[10]);

it only gives me the first entry in the php array so it seems like everytime the for loop is repeated its initialising the php file from scratch and so setting the counter to 0. How can i fix that?

like image 732
Tim Daubenschütz Avatar asked Mar 19 '12 16:03

Tim Daubenschütz


2 Answers

In php

//Bla being the php array you want to give to javascript. Create it however you like
$bla = array();
$bla[] = 'cat';
$bla[] = 'dog';
$bla[] = 'bat';
echo '<script>var myarray = '.json_encode($bla) .';</script>';

The above code will then output a script tag contain a varible called myarray, then contents of which will be JSON specifying the above array (json_encode formats the array in to javascript internal syntax- the array will probably look like ['cat','dog','bat] )

You can then get values from the JavaScript array as so:

<script>
 console.log(myarray[2]);
</script>
like image 153
Carl Avatar answered Sep 29 '22 21:09

Carl


Your PHP code is executed before your Javascript, thus it doesn't make sense to use it this way.

Instead, you should do something like this:

<?php for ($i=0;$i<48;$i++):?>
     name[<?php echo $i;?>] = "<?php echo giveJS();?>";
<?php endfor; ?>

In fact, if your PHP is that simple, you don't need a function:

<?php foreach ($names as $i=>$name):?>
    name[<?php echo $i;?>] = "<?php echo $name;?>";
<?php endforeah;?>

In both case, you'll have a Javascript like that:

name[0] = 'name0';
name[1] = 'name1';
...
name[47] = 'name47';
like image 34
haltabush Avatar answered Sep 29 '22 22:09

haltabush