CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002

    PHP & JavaScript Interaction

    Q: What is the extent of interaction between JavaScript and PHP?

    A: In order to answer this, you must be aware of some things. PHP is a server-side scripting language. This means that the PHP is executed on the server and the output is sent to the client's browser. The web browser cannot see the PHP nor can it execute it, it can only see the results or output. JavaScript is a client-side scripting language. This means that the server does not execute JavaScript, only the web browser does.

    JavaScript cannot directly interact with PHP because the PHP will always be executed first by the server and then sent to the client's browser. JavaScript can only pass information to PHP.

    Q: Can JavaScript variables be passed to PHP?

    A: Yes, they can but the methods are limited. Since PHP is always executed before JavaScript then the JavaScript variables must be passed through a form or the URL. Those are the only two options. Granted, you can use AJAX, but that still uses GET or POST. So, to retrieve these JavaScript variables, on the server-side, you will have to use $_GET or $_POST.
    PHP Code:
    // [url]http://www.example.com/?param1=value1[/url]
    $php_variable $_GET['param1'];

    // if using a form
    $php_variable $_GET['input_tag_name'];

    Q: Can PHP variables be passed to JavaScript?

    A: Yes, and it is very simple. Anything you echo or print to the browser becomes part of the direct source code. Simply echo the JavaScript you want.

    PHP Code:
    <script type="text/javascript">
      var javascript_variable = "<?php echo $php_variable?>";

    Q: How can JavaScript call a PHP function?

    A: It can't. PHP is always executed first and JavaScript has no control over PHP.

    Q: How can PHP call a JavaScript function?

    A: The same way that PHP variables are passed to JavaScript. Just output a call to the function. You may also pass parameters this way.

    PHP Code:
    <script type="text/javascript">
      <?php echo "function_name();"?>
    Last edited by PeejAvery; January 30th, 2008 at 07:12 AM.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

Posting Permissions

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

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.