converting a javascript variable into php variable

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
sumanbangladesh
Forum Newbie
Posts: 5
Joined: Tue Sep 18, 2007 2:41 am

converting a javascript variable into php variable

Post 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
anchises
Forum Newbie
Posts: 3
Joined: Thu Sep 27, 2007 5:42 am

Post 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.
sumanbangladesh
Forum Newbie
Posts: 5
Joined: Tue Sep 18, 2007 2:41 am

Post by sumanbangladesh »

Thank U for your replay
Post Reply