Forum Moderators: coopster

Message Too Old, No Replies

PHP variable into JS code

Insert a php variable in a Javascript code.

         

reversque

2:18 pm on Feb 2, 2010 (gmt 0)

10+ Year Member



Hello,

I have a slider/carousel and I need to insert a php variable in this code:

slider.data=[{"id":"slide-img-1","client":"nature beauty","desc":"nature beauty photography"},{"id":"slide-img-2","client":"nature beauty","desc":"add your description here"},{"id":"slide-img-3","client":"nature beauty","desc":"add your description here"},{"id":"slide-img-4","client":"nature beauty","desc":"add your description here"},{"id":"slide-img-5","client":"nature beauty","desc":"add your description here"}];


I want to replace
"desc":"nature beauty photography"
with
"desc":"$my_php_variable"


I've tried many ways but it didn't work.
Please help!

Thank you,
Emanuel

mattclayb

2:41 pm on Feb 2, 2010 (gmt 0)

10+ Year Member



You are having problems because Javascript is run on the client browser, and PHP is processed on the web server.

There for you cannot pass variables between the two.

Instead what you need to do is print the value of your variable into the source code of your Javascript. For example -

slider.data=[{"id":"slide-img-1","client":"nature beauty","desc":"<? echo $my_php_variable ?>"}]

This will echo the value of the variable, and render the contents into the source of your Javascript. The web browser can then process the Javascript and your variable along with it.

reversque

2:55 pm on Feb 2, 2010 (gmt 0)

10+ Year Member



The variable is not recognized that way even if is set, it returns nothing.

mattclayb

3:24 pm on Feb 2, 2010 (gmt 0)

10+ Year Member



Check that your variable contains data.

If the following line of code does not output anything, then the variable is empty and you need to look at more of your script.

<? echo $my_php_variable; ?>