0

I am playing with PHP and Javascript. Also I am trying to find all possible ways to pass javascript variable into php variable in the same php file. So far, I have found two possible ways. One is well known to everybody which is ajax (i,e calling another php file). But it could not solve my problem easily. Another solution that I have figured out is utilizing COOKIE/SESSION. Here is my simple code example: It will alert 5 to 10. Javascript variable value 5 is passing inside php variable =>

<div id="one">5</div>

<script>
var vall = document.getElementById("one").innerHTML;
document.cookie = "val="+vall;
alert('<?php   for($i=$_COOKIE["val"];$i<=10;$i++){echo $i;}  ?>');
</script>

Do you have any other alternate or better solution?

Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23
  • 4
    This won't work. PHP doesn't get the cookie until the next time you open the page. Remember that PHP runs when the page is created, it sends it to the client, then the client JS runs. – Barmar Jan 18 '23 at 15:56
  • I am trying to execute javascript function by php code. So, next time is not a problem. It is okey for one time only. But there is way of setting expiry time for for cookie – Asif Iqbal Jan 18 '23 at 16:01
  • You can't do that. JS runs on the client, PHP runs on the server. – Barmar Jan 18 '23 at 16:02
  • When you change the cookie in the browser, it doesn't send the cookie until the next time you open the page. You should use a form for this. – Barmar Jan 18 '23 at 16:03
  • See also: https://stackoverflow.com/questions/1917576/how-do-i-pass-javascript-variables-to-php – T.J. Crowder Jan 18 '23 at 16:10

0 Answers0