Page 1 of 1

converting a javascript variable into php variable

Posted: Sat Sep 29, 2007 1:40 am
by sumanbangladesh
hi
I am new in PHP and Javascript . I have to convert a javascript variable into php variable. I am trying in the following way
$phpVar="<script>document.write(MyVar)</script>";

echo $phpVar;---->this display the contents of MyVar

But
echo $phpVar[0];
echo $phpVar[1];
echo $phpVar[2];
.
.
.
.
doesnt display the contents of MyVar..

can any one help me.

Thanks in advance

Posted: Sat Sep 29, 2007 2:59 am
by anchises
I got stuck on something like this years ago when making a shopping cart. No straightforward solution that I know of.

Your solution doesn't work because the Javascript is processed by the client (your computer) after the page has been sent by the server (which is where the php is dealt with). So it's in the wrong order.

What you need to do is get your page to store the javascript variable somewhere (in a session, a cookie or a hidden form field), then call a php page to deal with it.

Something like this:

page1.php:

Code: Select all

<form .... action="page2.php"><input type="hidden" name="jsvar" value=""></form>
<script ...>[javascript function which produces the javascript variable ends with...] yourform.jsvar.value = _requiredvalue_ ; form.submit()</script>
page2.php:

Code: Select all

$jsvar = $_REQUEST['jsvar']
Obviously those snippets need a lot of working.

Difficult to know what the best solution is without knowing the context.

Or you could use Ajax.

Or even better - find another solution.

Posted: Sat Sep 29, 2007 4:16 am
by sumanbangladesh
Thank U for your replay