简体   繁体   中英

Converting a PHP variable to a JavaScript variable

I am making a pop up window with JavaScript using window.open() . The page to be opened should be stored in a variable.

That variable's name is determined using a PHP <form> . When the user clicks "confirm", it brings them to play.php?name=userinput , and when the window.open function is executed, it currently opens txtone.php . But I want it to open txtone.php?name=userinput , including that argument.

I can retrieve the value from the parent window ( name=userinput ), using a PHP variable, but I need to transform it into a JavaScript variable, and then use window.open(name); (The variable's name is name ).

So I am basically asking how do I convert a PHP variable into a JavaScript variable.

Making a PHP variable available in JavaScript happens when the page is generated. For example, assume you have a php variable called $name and you want a JavaScript variable called name. You normally define your JavaScript variable as:

var name='some value';

Instead, you will insert PHP:

var name='<?php echo $name; ?>';

Now, the value of $name in your PHP is also the value of name in your JavaScript at the moment that the page is dynamically created.

UPDATE: When I answered this, I should have explained further...

While the JavaScript and PHP variables have the same value, they are NOT the same variable. If you update $name in your PHP after your print the value to the JavaScript source code, it will not alter the JavaScript value. Similarly, if you change the value of the JavaScript variable, it will not change the value of the PHP variable. In other words, they are two completely separate and unrelated variables. The code above simply copies the value from PHP to JavaScript.

Try this :

where spge is variable in js

var spge = '<?php echo $status ;?>';

//suppose

<?php $tochange="from php to js" ?>

some where

//Head

    <script>

    function change(){

    var temp = document.getElementById("change").innerHTML;

    alert ("temp");

    }

    </script>

//body
<body  onload="change()" >


//create a invisible tag in body php document

    <span id="change"><?php echo $tochange ?></span>


.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM