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
converting a javascript variable into php variable
Moderator: General Moderators
-
sumanbangladesh
- Forum Newbie
- Posts: 5
- Joined: Tue Sep 18, 2007 2:41 am
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:
page2.php:
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.
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>Code: Select all
$jsvar = $_REQUEST['jsvar']Difficult to know what the best solution is without knowing the context.
Or you could use Ajax.
Or even better - find another solution.