You are not logged in.
Hi,
I'm getting nervous with dynamic javascript variable...
I have some variables in PHP like this:
$test['nice_one'] = 'abc';
$test['nice_two'] = 'qwe';
$test['nice_three'] = 'ghg';I wrote some javascript code, and I've got a var like this:
var foo = 'one'So... how can use foo to show (by alert, for example) the variable $test['nice_one'] ?
In php I got this by $test['nice_' . $foo . ']
Thank you.
Offline
You can't, php is server-side, javascript is client-side.
Once your js code starts, your php-code is already "locked", since the server "translates" it to html.
To make what you want to do, it requires a little more work, something like:
<script type='text/javascript'>
var foo = 'one';
if(foo=='one')
alert('<?php echo $test['nice_one'];?>');
elseif(foo='two')
alert('<?php echo $test['nice_two];?>');
elseif(foo='three')
alert('<?php echo $test['nice_three];?>');
else
alert('none);
</script>Last edited by mzneverdies (2013-09-11 09:58:29)
Offline
I suggest to sanitize the array, throw it at json_encode and then do something like
<script type='text/javascript'>
var foo = 'one';
var bar = <?php echo json_encode($test); ?>;
alert(bar['nice_'+foo]);
</script>If you need a more secure approach, read more here:
http://stackoverflow.com/questions/7229 … son-encode
Last edited by progandy (2013-09-11 10:12:02)
| alias CUTF='LANG=en_XX.UTF-8@POSIX ' | alias ENGLISH='LANG=C.UTF-8 ' |
Offline
Check out http://www.w3schools.com/ajax/ for more on ajax.
Offline