-2

I have been trying to pass javascript variable to php and it wont work dynamically, but works statically.

here is the dynamic code that does not work:

<input onClick="myFunction();" id="demoteTask" name="demoteTask" type="checkbox"/>Demote to Child
<script>
function myFunction() {
var parent = prompt("Please enter parent reskb id:", "");
<?php $new = "<script>document.writeln(parent);</script>" ?>
alert (<?php $new ?>);
}
</script>

here is the static code that worked:

<script>
var p1 = "hello";
</script>
<?php
$kk="<script>document.writeln(p1);</script>";
echo $kk;
?>

The dynamic code returns me null value in the alertbox.

Hello Man
  • 693
  • 2
  • 12
  • 29
  • 1
    You are missing the fundamental understanding of how the web works. PHP is a server side language, JavaScript is usually used as a client side language. When the client makes a request to a URL, your server will execute the PHP script and return the generated HTML to the client. The client will then parse the HTML and execute any JavaScript it contains. **PHP and JavaScript are executed on two different machines at different moments in time**. While you can mix their *source code*, you can't intermingle their behavior. – Felix Kling Jan 30 '15 at 05:41

1 Answers1

1

Why you're mixing server side and client side scripts. Server side scripts executes and sent packets to client.

Here in your code PHP will generate output as:

THIS

<input onClick="myFunction();" id="demoteTask" name="demoteTask" type="checkbox"/>Demote to Child</input>
<script>
    function myFunction() {
        var parent = prompt("Please enter parent reskb id:", "");
        // Here `$new` becomes server variable
        <?php $new = "<script>document.writeln(parent);</script>" ?>
        // and will prints here
        alert (<?php echo $new ?>);
    }
</script>

TO THIS

<script>
    function myFunction() {
        var parent = prompt("Please enter parent reskb id:", "");
        alert (<script>document.writeln(parent);</script>);
    }
</script>

FIX

Your should only use client side script. And there is no need to mix scripts. Server scripts can generate client scripts as server scripts variable. Here is my example:

<script>
    function myFunction() {
        var parent = prompt("Please enter parent reskb id:", "");
        alert(parent);
    }
</script>
Vin.AI
  • 2,369
  • 2
  • 19
  • 40