Trouble with PHP and JS

Discussion in 'PHP' started by chuckd1356, Jul 7, 2007.

  1. #1
    Here's my problem, I'm trying to make a php variable output into the javascript file. Could I do something like this?

    
    <script type="text/javascript" ... >
    /* ... */
    var <?=$text; ?>
    
    /* ... */
    
    
    
    Code (markup):
    Will that work?
     
    chuckd1356, Jul 7, 2007 IP
  2. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #2
    sure. just name the script file.js.php is what i normally do.
    and then the first line:

    
    <? header('content-type: text/javascript'); ?>
    
    PHP:
     
    ansi, Jul 7, 2007 IP
  3. chuckd1356

    chuckd1356 Active Member

    Messages:
    770
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    70
    #3
    So can I use a loop to echo javascript data?


    Now how do I go about using variables? Do I escape the php and put JS there?
    I'm sorry, but this makes my life so much easier.

    edit and off topic: you must be some super knowledge filled poster. You joined two months ago and have 200 more posts than me! Wow.
     
    chuckd1356, Jul 10, 2007 IP
  4. gibex

    gibex Active Member

    Messages:
    1,060
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    95
    #4
    yes, you can echo data from php into a js script

    ex:

    You can't walk through PHP arrays or objects in JS code. You can join arrays into strings and use them in Js code :

    last alert will display 1,2,3
     
    gibex, Jul 10, 2007 IP
    chuckd1356 likes this.
  5. chuckd1356

    chuckd1356 Active Member

    Messages:
    770
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    70
    #5
    Thanks bro. Worked perfectly.
     
    chuckd1356, Jul 10, 2007 IP
  6. gibex

    gibex Active Member

    Messages:
    1,060
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    95
    #6
    glad to help :D
     
    gibex, Jul 10, 2007 IP
  7. chuckd1356

    chuckd1356 Active Member

    Messages:
    770
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    70
    #7
    What do you mean "You can't walk through PHP arrays or objects in JS code"

    Couldn't I just loop through an array using document.write, or something, for each item?
     
    chuckd1356, Jul 10, 2007 IP