0

How can I store a JavaScript prompt value into a php variable? I tried some stuff but it did not work out. Here is is the code... I am doing it to pass the function mkdir(); in php , after getting the name of the folder from the prompt screen...

I simple have no idea, please help... The code is just a random try to do the same... i know it's wrong... thanks in advance...

<script language="java script">

    var php_var = "<?php echo "Hello!"; ?>";
    var variable= prompt("Hello",php_var);

</script>

<?php

$variable = "<script language=\"javascript\"> variable </script>";

?>
  • 3
    You can't, not like this anyway. PHP is processed on the server side, then once thats finished processing, and the page is displayed to the browser, Javascript is then ran. Therefore, javascript is run **after** php has finished. You will need to pass the variable value to your PHP script via ajax. – Phil Cross Sep 18 '14 at 14:55
  • Thank you... but a little more resources will help... – Prashanth Srinivas Sep 18 '14 at 14:56
  • 1
    `language="javascript"`? Why are you writing HTML 3.2? – Quentin Sep 18 '14 at 14:58
  • Could you save the response as a cookie then use the cookie value in PHP. Sloppy, but it should work. – espradley Sep 18 '14 at 15:21

1 Answers1

0

Javascript and PHP are not in sync. First PHP does it's job serverside (so not on the clients computer), then Javascript does (clientside, nothing to do with the server anymore).

There are some sneaky solutions though, for instance, jQuery's GET:

var answer = prompt('Puppies!?');
$.get('myFile.php', js_answer: answer);

Another one, a bit more difficult, but a fun method to explore (don't really recommend this):

var answer = prompt('Puppies!?');
var notReallyAnImage = document.createElement("img");
notReallyAnImage.src = 'myFile.php?js_answer='+answer;
document.body.appendChild(notReallyAnImage); 

This one will put your phpfile as image, this way the phpfile does get excecuted, allowing to pass information. Just don't forget to make php send headers like an image (can be 0x0/1x1px blank).

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • Great. Upvote if you think it's worth that and if it's your solution, mark this as the answer with the check on the left of the answer, so other people can see this works :) – Martijn Sep 18 '14 at 15:03