Page 1 of 1

php to javascript

Posted: Thu Apr 03, 2003 7:17 pm
by nincha
whats the syntax to send a php variable to javascript (if possible) and the other way around???

Posted: Thu Apr 03, 2003 7:50 pm
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.