eager2learn — 2010-08-11T05:47:07-04:00 — #1
I've been workling seperately with PHP/ MySQL and am now trying to get things together with jQuery which I have so far only used with non-dynamic content. Here is the setting I am trying to achieve:
I have one php file that generates two different contents depending on the setting of a status-variable $ncs. If $nsc=0 the main page is loaded, showing an overview of all available news-articles. If $ncs=1 the content of a specific article is shown fully. The jQuery connected to each case differs. So i would like to pass the varible $ncs over to my jQuery script:
var status = "<?php echo $ncs; ?>";
I have checked that $ncs is not NULL on the rendered page. However after being passed to the jQuery script the variable is undefined. I have never connected PHP and jQuery so it is probably a general twist in my idea of how it works. I tried passing different variables and all are undefined in jQuery. What do I have to attend to when passing PHP-variables to jQuery?
Any help apprechiated :).
eager2learn — 2010-08-11T14:06:40-04:00 — #2
OK. So obviously I did get the whole concept wrong.
Defining a js-variable in a PHP-file works while placing my code in the *.js will not function? Did I get that right?
Is there another way to hand over PHP-variables to a JS/ jQuery file?
I will try your solution...
rnel — 2010-08-11T13:59:49-04:00 — #3
var status = "<?php echo (int) $ncs; ?>";
<?php echo (int) $ncs; ?>
will not be rendered as you want on a js file
I added (int) function to make sure it returns an integer value rather than empty if $ncs=''
rnel — 2010-08-11T15:50:09-04:00 — #4
yep defining correct js variable on a php file will work, on the other hand php codes do not work on a js file. remember that js works on a client side while php is on the server side. that's pretty much simple explanation why php codes won't work on a js file.
as far as i know there are several tricks to pass php values on a js file but it will all initiate on a php file before going down to a js file, you can also write your js codes on a php file just like the example above.