1

I'm fairly new to programming in Javascript and I can't find broad documentation on how to create a PHP variable from a javascript variable. Can somebody please show me an example of this? In the following example, 't' is the Javascript variable that I want to use in PHP:

    <script type="text/javascript">
        function readtime(){
             var d = new Date();
             var c_hour = d.getHours();
             var c_min = d.getMinutes();
             var c_sec = d.getSeconds();
             var t = c_hour + ":" + c_min +":" + c_sec;
                           }
    </script>
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 2
    PHP runs on the server, JavaScript in the browser, so they can't directly communicate with each other. (There is Ajax, but that's probably not going to be practical in this specific instance.) – Pekka Jun 10 '13 at 16:29
  • I believe you are looking for an AJAX solution. http://www.tizag.com/ajaxTutorial/ajaxphp.php – JonnyS Jun 10 '13 at 16:29
  • Since you're giving the direct time stamp, why not just give the `d.getTimezoneOffset();`? This will let PHP know exactly what time the user is at. – Dave Chen Jun 10 '13 at 16:32

6 Answers6

2

As all PHP script is ran on the server there is no way to do this without AJAX after or on page load, but that might defeat the purpose of the PHP variable. You can however define a javascript variable with a php variable.

<?php
  $foo = "bar";
?>
<script type="text/javascript">
  foo = '<?php echo $foo; ?>';
  alert(foo);
</script>

I would take a look at PHP date function as well if all you need is to get the date and time into a php variable.

amaster
  • 1,915
  • 5
  • 25
  • 51
  • `echo json_encode($foo)`. Other than that, the snippet will work. – John Dvorak Jun 10 '13 at 16:38
  • Thank you for the help and clarification of what ineractions are possible directly between Javascript and PHP. – David Schilpp Jun 10 '13 at 16:48
  • Just a note, you should never do `foo = '';` If some reason $foo contains a ' then it will cause an error. You should instead map it to an array or object, and use `foo = ` – Steven Jun 10 '13 at 16:50
  • @JanDvorak I have just tested this again and use similar code in a production. It works. I had to edit the answer to include the quotation marks for defining the JavaScript variable and all works fine. Test yourself if desired. – amaster Jun 10 '13 at 16:50
  • @Steven thank you for this which is true data. however if you control the php variables and only allow a set defined string then it will work which is what I have done. If you do not control the variable then your way is best. – amaster Jun 10 '13 at 16:52
2

As others have mentioned, PHP runs on the server - Javascript runs on the client. I thought that you might appreciate some more detail into what this means, and why there's no 'easy answer' to how to do this.

The server is the computer on which the code is being stored.
The client is the browser you are viewing the resultant pages upon.
This might be on the same computer, especially while testing, but they are still considered to be separate entities.

When running PHP + Javascript apps:

1: The browser makes a request to the server.
2: The server pulls up the relevant PHP, crunches it, and inserts it into the html in the appropriate places.
3: The resultant data (html + javascript) is sent across the internet to the browser, which receives it.
4: The browser displays the raw data (as html).
5: The browser crunches the javascript and changes the html accordingly.
6: Additional activity on the page can cause constant repetition of #4, or a return to #1.

Now, the reason people are recommending Ajax calls is as follows: An Ajax call will make a request to the server 'in the background'. It doesn't cause a page reload, therefore step #4 is skipped. It simply receives the relevant data, processes it, and makes changes to the already existing html as needed.

But what this also means is that you can send a request to the server to please run a specific section of PHP - to save data to the database, to request a new piece of data, to run a calculation ...

However. Each type of request needs its own new access point in the PHP - a PHP page without html, if you will. Json is usually the data format of choice for transfer, though xml (the X in AJAX) is also still used.

This is not a simple act, and causes a lot of complication in the code ... but because PHP can build javascript, but javascript cannot directly affect the PHP, making the transfer of data usually a one-way street, this is the only way to bring javascript results back to the server so that PHP can handle it. You cannot just 'change a PHP variable' - you need to start the PHP from scratch once again, and initialize all relevant variables, in order to get the proper result. You're not picking up where you left off, you're making a brand new request.

Hope this helps!

Wolfman Joe
  • 799
  • 1
  • 8
  • 23
  • Thank you for the in-depth explanation of Javascript/PHP interactions as well as how AJAX works. All of the information that you provided is relevant and helpful. Thanks again! – David Schilpp Jun 10 '13 at 17:08
1

You can send your javascript variable to a php page via ajax call.this is how you do it

    function loadXMLDoc()
    {
var a=document.getElementById('id').value//this is your js variable to be sended to a php page
    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
       //response
        }
      }
    xmlhttp.open("GET","Xyz.php?variable="+a,true);
    xmlhttp.send();

    }

then on your php page get the values by using $_REQUEST['variable']

    $PHP_variable=$_REQUEST['variable'];
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87
0

If you want to use your variable in PHP for some reason, the only way is via Ajax calls. That will send the variable to the server, you will be able to treat it like you want and will be able to send it back to the Ajax and do what you want in your page.

But you won't be able to use the result of your Javascript in your PHP like if you were converting from JS to PHP because JS is client side and PHP server side.

Jay Zus
  • 573
  • 5
  • 19
  • Thank you for that clarification. Isn't that partially because if Javascript could directly interact with PHP, then users could easily manipulate webpages in any way they want? – David Schilpp Jun 10 '13 at 16:57
  • Yes, since JavaScript is client sided, if it could directly interact with your server, it could be potentially harmfull because anyone could modify the script to send anything they want to your server. – Jay Zus Jun 10 '13 at 16:58
0

No, not without AJAX (which wouldn't work in this instance). PHP is a server side language that is used to generate a webpage, which the webserver then sends to the user. Javascript is a client-side language (runs in the user's browser); as such, it always runs after all the PHP has finished. You can use PHP to generate JavaScript, but not the other way around.

In PHP, to get the current time in that format, use $currentTime=date('h:i:s').

IanPudney
  • 5,941
  • 1
  • 24
  • 39
  • you answered my question the fastest with accurate information as well as a solution to my particular example. Thank you! – David Schilpp Jun 10 '13 at 16:46
0

PHP runs on the server; when the browser is executing javascript (if it does - you can never be sure) php is not running anymore. In this case you can likely move that whole logic to php, using its date objects/functions. There are a few ways to do it:

  • if you were about to pass control to some php code (request a new page or AJAX call) the time could either be computed by php as part of whatever it has to do or passed to it as a GET or POST parameter.
  • if the t variable just has to be printed on screen, the main page can do it on the php side
Rad80
  • 823
  • 7
  • 17