Reputation: 31
I need to pass a value from javascript to php. How can i achieve this since one runs on client side and other on server? or any other alternatives for this to happen? I am a newbie in programming, so correct and suggest me if i am wrong.
<html>
<head>
<SCRIPT language="JavaScript">
var q1=Math.floor(Math.random()*11)
<?php
$ff = q1;
?>
</SCRIPT>
</head>
<body>
<?php
echo $ff ;
?>
</body>
</html>
Upvotes: 0
Views: 32763
Reputation: 368
you can use like this.
<html>
<head>
<script type="text/javascript">
var q1="hello";
<?php
$ff ="<script>document.write(q1)</script>";
?>
</script>
</head>
<body>
<?php echo $ff; ?>
</body>
</html>
Upvotes: 1
Reputation: 63
you can use like this.
<html>
<head>
<script type="text/javascript">
var q1="hello";
<?php
$ff ="<script>document.write(q1)</script>";
?>
</script>
</head>
<body>
<?php echo $ff; ?>
</body>
</html>
Upvotes: 0
Reputation: 12127
PHP is server side language, that is used to render output in HTML, so you can assign PHP variable in JavaScript variable not JavaScript to php, you can send JavaScript variable to Server by AJAX
Try this way
<SCRIPT language="JavaScript">
var q1=Math.floor(Math.random()*11)
function sendAJAX(q1)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert('posted value' + xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://yourdomain.com/?q=" + q1 ,true);
xmlhttp.send();
}
</SCRIPT>
And in PHP code
<?php
$ff = $_GET['q'];
echo $ff;
?>
Upvotes: 2
Reputation: 1688
The HTML file:
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
var q1=Math.floor(Math.random()*11);
$(document).ready(function(){
$.ajax({url:"ajax.php",data: {"q1":q1}}).done(function(data){console.log(data)});
});
</script>
The PHP file: ajax.php
<?php
$ff = filter_input(INPUT_GET, 'q1', FILTER_VALIDATE_INT);
echo $ff;
?>
References:
Upvotes: 1
Reputation: 4222
It is not possible since PHP code (server-side) is run/parsed before javascript code (client side). So what you are doing is not possible although reverse is possible. You can also use:
To send javascipt variable value to php.
Upvotes: 3