php to javascript

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
nincha
Forum Contributor
Posts: 191
Joined: Fri Mar 28, 2003 12:30 pm
Location: CA, USA

php to javascript

Post by nincha »

whats the syntax to send a php variable to javascript (if possible) and the other way around???
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

you can write the content of a php-variable in a way that the client-side javascript engine interprets it as varaibale for js.
Javascript on the other hand can add parameters to the request that php can handle.

Code: Select all

<?php
$r = rand(1,100);
$c = (isset($_POST['hiddenCounter'])) ? $_POST['hiddenCounter']:0;
?>
<html>
	<head>
		<script type="text/javascript">
			function addValue(oForm)
			{
				oForm.hiddenField.value = "<?php echo $r; ?>";
				oForm.hiddenCounter.value = <?php echo $c; ?>+1;
				return true;
			}
		</script>
	</head>
	<body>
		<pre>
			<?php print_r($_POST); ?>
		</pre>
		<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" onSubmit="addValue(this);">
			<input type="hidden" name="hiddenField" />
			<input type="hidden" name="hiddenCounter" />
			<input type="submit" />
		</form>
	</body>
</html>
request the document and open it in your browser's source view to see what the client-side interpreter does.
Post Reply