user1219906
user1219906

Reputation: 1

How to add ( or attach ) variable on variable in JS

i stuck to attach counter-var (b) on text-variable (string) - not mathematical - Just to add counter(b) on data-var in JS...

Example:

<script type="text/javascript">    

<?php 
$i=0;
foreach ($sqldata as $data){
echo 'var data'.$i.' = 
Array("'.implode('", "', array_map('addslashes', $data)).'");';     
$i++;
}
echo 'var data_ges = '.$i.' ;';
?>

for (b=0; b<data_ges; b++){
document.writeln (data+b[1]); // ERROR LINE - How do i escape here ?
}

</script>

Thanks!

Upvotes: 0

Views: 190

Answers (3)

djd
djd

Reputation: 5178

Your php is making a set of variables like data0, data1. One way to capture these back is to grab them off the this or global window object:

for (var i = 0; i < data_ges; ++i) {
  document.writeln(window['data' + i]);
}

It would probably be better to actually make an array called data in the php though:

var data = [];
<?php 
foreach ($sqldata as $data) {
    echo 'data.push(' … ');';
}    
?>

for (var i = 0; i < data.length; ++i) {
  document.writeln(data[i]);
}

Upvotes: 0

Sebastian Stiehl
Sebastian Stiehl

Reputation: 1888

You can use the json_encode function to create a javascript-object where you can easily iterate over. http://www.php.net/manual/en/function.json-encode.php

Upvotes: 1

dievardump
dievardump

Reputation: 2503

You should just use array instead of trying to dynamically use a variable name :

<script type="text/javascript">    
  var data = [];
<?php 
$i=0;
foreach ($sqldata as $data){
echo 'data['.$i.'] = 
Array("'.implode('", "', array_map('addslashes', $data)).'");';     
$i++;
}
?>

for (b=0, l = data.length; b<l; b++){
document.writeln (data[b]); // ERROR LINE - How do i escape here ?
}

</script>

Upvotes: 1

Related Questions