You are not logged in.

#1 2013-09-11 09:43:08

monotiz
Member
Registered: 2007-10-20
Posts: 140

Javascript+PHP: dynamic variable issue...

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

#2 2013-09-11 09:48:51

mzneverdies
Member
Registered: 2012-02-04
Posts: 147

Re: Javascript+PHP: dynamic variable issue...

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

#3 2013-09-11 10:02:33

progandy
Member
Registered: 2012-05-17
Posts: 5,307

Re: Javascript+PHP: dynamic variable issue...

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

#4 2013-09-11 15:52:10

cookies
Member
Registered: 2013-01-17
Posts: 253

Re: Javascript+PHP: dynamic variable issue...

Check out http://www.w3schools.com/ajax/ for more on ajax.

Offline

Board footer

Powered by FluxBB