Home Top Projects Tutorials Articles Submit Project
 
  • .NET Frameworks
  • Java Frameworks
  • PHP Frameworks
  • Ruby Frameworks
  • Other Frameworks
  • Cool AJAX sites
  • Ajax Resources
  • Ajax Tools
  • JavaScript frameworks
 
     
    • Creating an Autosuggest Textbox with JavaScript, Part 2
    • Creating an AJAX-Style Animated Loading GIF
    • Faking an AJAX upload script
    • Niceforms
    • AJAX Chat Tutorial
    • ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender
    • Creating an AJAX-Enabled Grid (Part 2)
    • Cross Domain Ajax Calls ASP.NET MVC
    • Working with Exceptions using ASP.NET Ajax
    • Javascript Rotation Image
    Home » Tutorials » Passing JavaScript Value to PHP

    Passing JavaScript Value to PHP

    Recently, I received an email from a regular reader of WebDev, ‘nurmala.’ He/She wanted to know how you can pass a value written in Javascript to a PHP Variable.

    Before I get into the neat details, let me give you a quick overview of the main differences between Javascript and PHP.

    Javascript is a client scripting language. Whatever you code in Javascript will work only in the web browser of the user. So, if the user turns off Javascript in his web browser, your website will basically just drop dead.

    PHP is a server side scripting language. Now, what this does is, it runs in the server. So, the user can’t really turn it on or off, but you can, because you have control over the server script.

    Can they work together? Definately!


    How Data are Passed

    There are two main methods used to pass data between Javascript and PHP. A Javascript function will need to execute a PHP Script directly behind the scenes with the data or you can use javascript to store the value in a hidden field, and after the form is submitted to a PHP page, simply retrieve the data.
    The Classic But Easy Way (Requires Form Submission)

    You can see a demo of this method here: http://www.web-development-tutorials.com/demo/HowToPassValueBetweenPHPnJS/classic/

    classic.html
    view plaincopy to clipboardprint?

       1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
       2. <html xmlns="http://www.w3.org/1999/xhtml"> 
       3. <head> 
       4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
       5. <title>Classic Example</title> 
       6. <script language="javascript" type="text/javascript"> 
       7. var MyJavascriptVariable = "Megan Foxx"; 
       8.  
       9. function SetJsValue() 
      10. { 
      11.     document.classic_form.jsvalue.value = MyJavascriptVariable; 
      12. } 
      13.  
      14. </script> 
      15. </head> 
      16.  
      17. <body> 
      18. <form action="action.php" method="post" enctype="application/x-www-form-urlencoded" name="classic_form" id="classic_form"> 
      19.     <input type="hidden" name="jsvalue" id="jsvalue" value="javascript:MyJavascriptVariable.toString()" /> 
      20.     <input type="submit" name="submit" id="submit" value="Submit" onclick="SetJsValue();" /> 
      21. </form> 
      22. </body> 
      23. </html> 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Classic Example</title>
    <script language="javascript" type="text/javascript">
    var MyJavascriptVariable = "Megan Foxx";

    function SetJsValue()
    {
     document.classic_form.jsvalue.value = MyJavascriptVariable;
    }

    </script>
    </head>

    <body>
    <form action="action.php" method="post" enctype="application/x-www-form-urlencoded" name="classic_form" id="classic_form">
        <input type="hidden" name="jsvalue" id="jsvalue" value="javascript:MyJavascriptVariable.toString()" />
        <input type="submit" name="submit" id="submit" value="Submit" onclick="SetJsValue();" />
    </form>
    </body>
    </html>

    Just save the above code as classic.html. And let me explain what is going on in here.

    Before the </head> tag, I declared my Javascript variable called MyJavascriptVariable. Then, you will see the JavaScript function SetJsValue(). This function is executed after the submit button is clicked on the form.

    And in the actual HTML form itself I have a hidden field called ‘jsvalue.’ After the submit button is clicked, the SetJsValue() kicks in, it sets the value of the hidden field to whatever value is in the ‘MyJavascriptVariable’ and submit the whole form to the action.php page.

    action.php
    view plaincopy to clipboardprint?

       1. <?php 
       2.  
       3. if(isset($_POST['submit'])) 
       4.     echo "The javascript value is: ".$_POST['jsvalue']; 
       5.  
       6. ?> 

    <?php

    if(isset($_POST['submit']))
     echo "The javascript value is: ".$_POST['jsvalue'];

    ?>

    All action.php page is doing is retrieving the HTML input fields from the $_POST superglobal variable, and this way it gets access to the value of the javascript value.
    The Modern But Slick Way

    If you know about PHP Sessions, then you know how powerful and useful it is to store data for some period of time. Here’s a very cool trick you can use to pass data stored in a JavaScript variable to a PHP Page.

    modern.html
    view plaincopy to clipboardprint?

       1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
       2. <html xmlns="http://www.w3.org/1999/xhtml"> 
       3. <head> 
       4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
       5. <title>Modern Way</title> 
       6. <script language="javascript" type="text/javascript" src="jquery.js"> 
       7. </script> 
       8. <script language="javascript" type="text/javascript"> 
       9. var MyJavascriptVariable = 'Kate Winslet'; 
      10.  
      11. $(document).ready(function() 
      12. { 
      13.     $.post("ajax.php", { js: MyJavascriptVariable}); 
      14. }); 
      15. </script> 
      16. </head> 
      17.  
      18. <body> 
      19. <p>Javascript already posted the value stored in the javascript variable 'MyJavascriptVariable.'</p> 
      20. <p>Visit <a href="sample-php-page.php">sample-php-page.php</a> now, and you will see it waiting for you.</p> 
      21. </body> 
      22. </html> 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Modern Way</title>
    <script language="javascript" type="text/javascript" src="jquery.js">
    </script>
    <script language="javascript" type="text/javascript">
    var MyJavascriptVariable = 'Kate Winslet';

    $(document).ready(function()
    {
     $.post("ajax.php", { js: MyJavascriptVariable});
    });
    </script>
    </head>

    <body>
    <p>Javascript already posted the value stored in the javascript variable 'MyJavascriptVariable.'</p>
    <p>Visit <a href="sample-php-page.php">sample-php-page.php</a> now, and you will see it waiting for you.</p>
    </body>
    </html>

    In this basic HTML Web page, I included the jQuery library. jQuery is a Javascript library you can use to speed things up with Javascript. And it makes making AJAX calls super duper easy. You can download jQuery from http://jquery.com/
    view plaincopy to clipboardprint?

       1. var MyJavascriptVariable = 'Kate Winslet'; 
       2.  
       3. $(document).ready(function() 
       4. { 
       5.     $.post("ajax.php", { js: MyJavascriptVariable}); 
       6. }); 

    var MyJavascriptVariable = 'Kate Winslet';

    $(document).ready(function()
    {
     $.post("ajax.php", { js: MyJavascriptVariable});
    });

    The variable MyJavascriptVariable is just a normal javascript variable with the value ‘Kate Winslet’. Next, using jQuery I am posting the value to ajax.php page only after the HTML document is fully loaded. And behind the scene, the ajax.php page will take the value and store it in a PHP Session.

    So, when the user visits sample-php-page.php, the value is already set.

    ajax.php
    view plaincopy to clipboardprint?

       1. <?php 
       2.  
       3. session_start(); //start PHP Session 
       4.  
       5. $_SESSION['jsvalue'] = $_POST['js']; //store the posted value in a php session variable 
       6.  
       7. ?> 

    <?php

    session_start(); //start PHP Session

    $_SESSION['jsvalue'] = $_POST['js']; //store the posted value in a php session variable

    ?>

    sample-php-page.php
    view plaincopy to clipboardprint?

       1. <?php 
       2.  
       3. session_start(); //start session, later display the javascript value stored in session. 
       4.  
       5. ?> 
       6. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
       7. <html xmlns="http://www.w3.org/1999/xhtml"> 
       8. <head> 
       9. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
      10. <title>Sample PHP Page</title> 
      11. </head> 
      12.  
      13. <body> 
      14. This is a PHP Page. The javascript value is: <?php echo $_SESSION['jsvalue']; ?> 
      15. </body> 
      16. </html> 

    <?php

    source: web-development-tutorials

    Copyrights Reserved AjaxProjects.com 2006-2013, Powered by Enozom - Mobile Development Company -Privacy Policy