Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jan 2010
    Location
    In a dump
    Posts
    64
    Thanks
    9
    Thanked 2 Times in 2 Posts

    PHP and Javascript

    I have a wrote some php which has some value and I wanted to pass a javascript function the php value while calling the javascript from php.

    I know I can call the function of the javascript from an echo in the php however I want to call the function more than once throughout the whole of the php and pass different variables so I wrote some php variables to contain the first bit and the last bit of the javascript for example:
    PHP Code:
    $js '<script language = Javascript>';
    $js2 '</script>'
    then in invoked the function like so:

    PHP Code:
    echo($js'setCookie("name_iARC",' .$info['fName'].')' .$js2); 
    $info is the variable from the array that I require to pass, this parses fine but it does not work. Any ideas why? have I done something wrong somewhere?

    Thanks.
    Last edited by InterbredMonkey; 01-27-2010 at 03:44 PM.

  • #2
    Senior Coder Len Whistler's Avatar
    Join Date
    Jul 2002
    Location
    Vancouver, BC Canada
    Posts
    1,323
    Thanks
    26
    Thanked 100 Times in 100 Posts
    This works.

    PHP Code:
    <?php
    $f_name 
    "John Smith";
    ?>

    <script language="JavaScript">
    function setCookie(c_name,value) {
    document.cookie=c_name+ "=" +escape(value);
    }

    var php_variable="<?php echo "$f_name"?>";

    setCookie('cookie_name',php_variable);
    </script>


    -------------------
    Leonard Whistler

  • Users who have thanked Len Whistler for this post:

    InterbredMonkey (01-27-2010)

  • #3
    New Coder
    Join Date
    Jan 2010
    Location
    In a dump
    Posts
    64
    Thanks
    9
    Thanked 2 Times in 2 Posts
    Thank you Len,

    I have sorted it now, I wrote all the code for the javascript into the PHP echo. I forgot I needed to break out of the javascript and add the php variable.

    Done like so if anyone else gets stuck...

    PHP Code:
    echo("<script language = Javascript>setCookie('username', \"$user\")</script>"); 
    Notice you have to wrap the variable..

    PHP Code:
    " \"$user\" 
    Sorted.


  •  

    Posting Permissions

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