javascript call function from php file! (using yii)

Discussion in 'JavaScript' started by caughtfromabove, Oct 24, 2012.

  1. #1
    [TABLE]
    [TR]
    [TD="class: votecell"]

    [/TD]
    [TD="class: postcell"] I'm trying to call a function in a .js file from the php page where I'm displaying it!
    What I want to do is something like this:
    .php file:

    ...
    function testFunc(){
    return "2";
    }
    ...
    now I want to call this function inside the .js file!
    Thaks in advance for your help


    [/TD]
    [/TR]
    [/TABLE]
     
    caughtfromabove, Oct 24, 2012 IP
  2. knewedge

    knewedge Active Member

    Messages:
    37
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #2
    If I'm reading you correctly I would put your JavaScript in your PHP file and then you can echo PHP information into your JavaScript.

    Example:
    <?php
    function test(){
    return 2;
    }
    ?>
    <script>
    var test = "<?php echo test(); ?>";
    </script>
     
    knewedge, Oct 27, 2012 IP
  3. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #3
    PHP runs on the server and creates the page (including any Javascript on the page). It then sends the page to the user.

    Any Javascript on that page runs in the user's browser. It has nothing to do with the PHP that created it.

    If you want to communicate back and forth between the browser and the server (where you can run a PHP file), you'll have to use AJAX.

    But you can't run Javascript on the server to give PHP some values to use in the page it's creating. It creates the Javasceipt and sends it to the browser to run. It's two totally seperate operations, and AJAX is about the only way to communicate back and forth between them - from an already-created (and running) page and the server (and back).
     
    Rukbat, Oct 27, 2012 IP