1

I am Trying to JavaScript Variable to assign PHP Variable and my Value to Alert but Getting on error the output as "; alert(simple);

var p1sds = "My Custom String";
<?php
$dsfd = "<script>document.writeln(p1sds)</script>";
?>
    var simple = "<?php echo $dsfd ;?>";
      alert(simple);

</script>
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Ranjith
  • 165
  • 15

3 Answers3

0

i needed to do something like this a while ago i used cookies

setCookie("p1sds","My Custom String")
<?php
$dsfd = $_COOKIE["p1sds"]
?>
    var simple = "<?php echo $dsfd ;?>";
      alert(simple);
Steve Fox
  • 46
  • 3
  • yes but my custom string output only JavaScript Value for assign variable as var p1sds = "My Custom String"; its that .. – Ranjith Sep 24 '16 at 04:54
0

It is impossible for you to set PHP variable based off of JavaScript variables, because as far as the JavaScript is concerned, there is no PHP. It's just HTML being echoed or included.
You can do it the other way around (how you have it in cookies) because the PHP will run first and be able to set the variables before the JavaScript runs.

In your example, when you set $dsfd to $dsfd = "<script>document.write...<script>", unless you do something more with $dsfd later, there is no effect.

If you are ok with the idea of using more than one page, then you can probably do something with cookies, but then you have to go from page to page to accomplish what you want, and that might be not an options because of something else.

My last thought on this is that you might be able to use something like hidden <iframe> elements using PHP to echo variables when the <iframe> loads or reloads, but I've never done something like that so I can't say.

Hope something in here is helpful.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
RedXTech
  • 406
  • 2
  • 7
  • 17
0

Hi I am just changed the following Thinks its Working

var p1sds = "My Custom String";
 document.cookie='p1sds='+p1sds; 

<?php
if (isset($_COOKIE["p1sds"])) {
 $asdas= $_COOKIE["p1sds"]; 
}
?>
   var simple = "<?php echo $asdas ;?>";
      alert(simple);

</script>
Ranjith
  • 165
  • 15