SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Passing PHP variables not working

    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:

    Code JavaScript:
    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 .
    Sam

  2. #2
    SitePoint Zealot
    Join Date
    Jul 2010
    Posts
    112
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    be sure you put this javascript code on a PHP file

    Code JavaScript:
       var status = "<?php echo (int) $ncs; ?>";

    because this
    PHP Code:
    <?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=''

  3. #3
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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...
    Thanx!

    Sam

  4. #4
    SitePoint Zealot
    Join Date
    Jul 2010
    Posts
    112
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •