...

View Full Version : javascript var value outside javascript



sunnynosid
01-03-2012, 08:09 AM
This is my javascript:

<script type=text/javascript>
function alert(){var value=1; alert("value");}
</script>

<?php
Some Code....
?>

Now i want to convert "var value" in to php variable in my php script on the same page. How can i do it?

Amphiluke
01-03-2012, 08:22 AM
It's not quite clear what you are trying to achieve. If you need a php variable, just declare it.


<?php $php_var = 1; ?>

<script type=text/javascript>
function alert(){var value=<?php echo $php_var; ?>; alert("value");}
</script>

<?php
// Some Code...
?>

Old Pedant
01-03-2012, 08:30 AM
This is my javascript:

<script type=text/javascript>
function alert(){var value=1; alert("value");}
</script>

<?php
Some Code....
?>

Now i want to convert "var value" in to php variable in my php script on the same page. How can i do it?

You can't. Period.

The ONLY way to send the value of a JavaScript variable to PHP code is to make an HTTP Request of the PHP server and get back an HTTP Response.

You can do that by
(a) submitting a <form>
(b) using location.href="somephppage.php?value=" + value
(c) using AJAX

Read post #2 in this thread:
http://www.codingforums.com/showthread.php?t=247585

sunnynosid
01-03-2012, 08:40 AM
I think this would make clear to you.
This is my script:

<html>
<head>
<script type=text/javascript>
value=1
value=<?php $num?>;
</script>
<?php echo"$num";?>
</head>
</html>

I am trying to convert the javascript variable "value" in to php variable "$num".
Is this script correct for that? If not correct then please correct it.

Amphiluke
01-03-2012, 08:50 AM
If the JavaScript variable value may dynamically change, then consider Old Pedant's suggestions.

Old Pedant
01-03-2012, 09:05 AM
I can't make any sense of that script, anyway.

First you set the JavaScript variable value to 1.

Then you change it to equal the value of the PHP variable $num.

No place do you even attempt to change the PHP variable to be equal to the JavaScript variable. WHich is a good thing, because you can't do it.

Dormilich
01-04-2012, 01:19 PM
I may add that JS and PHP have different execution times. namely PHP first and way after that JS. hence to pass a value from JS to PHP use the suggestions from Old_Pedant.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum