JavaScript & PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
maskme
Forum Newbie
Posts: 6
Joined: Sun Jul 28, 2002 9:27 am

JavaScript & PHP

Post by maskme »

Dear All

First I'm trying to get the Client Date & Time using JavaScript.
After that I'm passing the JavaScript Variable to the PHP Variable (Which Im not sure is the right way).
When I echo the JavaScript Variable It displays.

But the problem is the the variable $dor consists of <script langauge="JavaScript"> document.write (da) </script> I just want the value of javascript variable da. Im stuck, How to pass a value of JavaScript variable into a PHP variable.

Please Help :(

See code below
---------------------------------

Code: Select all

<script language="JavaScript">
var mydate=new Date();
var temp=mydate.getMonth()+1
var da;
document.write("Todays date \t:\t");
var da = mydate.getDate() + "/" + temp + "/" + mydate.getYear();
document.write(da);
document.write("System time \t:\t");
document.write(mydate.getHours() + ":" + mydate.getMinutes() + ":" + mydate.getSeconds());
</script>

<?
$dor = "<script language=JavaScript> document.write(da) </script>";
echo $dor; // Displays the Date Of Client Side
//Coverting Date in to MySQL Format
echo "Original Date ".$dor; 
$y = substr($dor, 6, 10);
$d = substr($dor, 0, 2);
$m = substr($dor, 3, 2);
echo "<br>Year ".$y; 
echo "<br>Day ".$d;
echo "<br>Month ".$m;
$ndor = "$y-$m-$d";
echo "<br>New Date ".$ndor;
?>
---------------------------

Thanx a lot
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

PHP is server-side and it's code has been executed before the Javascript (which is client-side) does anything. You cannot therefore pass variables directly between them. You can put the javascript variable into the URL as part of the query string, or into a cookie, or post it using a form and reload the page, then you will be able to use PHP to access the variable.

Mac
User avatar
phpScott
DevNet Resident
Posts: 1206
Joined: Wed Oct 09, 2002 6:51 pm
Location: Keele, U.K.

javascript to php

Post by phpScott »

twifletmac is right javascript can't be passed dirrectly to the php because of where the code executes.
The easyest way i find to pass javascript to php is to use the javascript to set a hidden field in the html form then submit the form.

ie:
document.someFormName.hiddenFieldName.value=javascriptVariableName;

document.someFormName.submit();

this last line will submit the form and pass the info along to the same script as in your action field in your form.

where the hidden field name is the same name as the php variable you wish to use.

hopefully that is of some use

phpScott
Post Reply