I am trying to open a new window, with its content coming from PHP code. I need to have the value $MsgWindow passed to the:
myWindow.document.write(something); statement in the JavaScript.
So far I've been unsuccessful in doing it.
Any suggestions?
<!DOCTYPE html>
<html>
<?php>
$info = array($_GET["airport"],
$_GET["state"],
$_GET["distance"],
$_GET["price"]);
$fin=array();
foreach ($info as $value) {
$value = substr($value, 2);
$value=substr($value, 0, -2);
array_push($fin,$value);
}
$airport = $fin['0'];
$state = $fin['1'];
$distance= $fin['2'];
$price = $fin['3'];
$MsgWindow="Your estimate to ".$airport." ".$state. " is ".$price;
echo $MsgWindow;
echo "<br>";
?>
<p>Click the button to write some text in the new window and the source (parent) window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var myWindow = window.open("", "myWindow", "width=200, height=100");
myWindow.document.write(something);
myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>
</html>
2 Answers 2
You could do the following. The variable is proccessed by php, and it appears as valid javascript code:
<script type="text/javascript">
var php_var = "<?php echo $MsgWindow; ?>";
</script>
I would like to note that if $MsgWindow has quotes, it will break the script. You will have to use addshlashes to get around that.
2 Comments
Because you are building the javascript code as part of the execution of the PHP script, you can simply echo out the PHP variable where you want to use it in the javscript fragment.
Like this :
<!DOCTYPE html>
<html>
<?php
$info = array($_GET["airport"],
$_GET["state"],
$_GET["distance"],
$_GET["price"]);
$fin=array();
foreach ($info as $value) {
$value = substr($value, 2);
$value=substr($value, 0, -2);
array_push($fin,$value);
}
$airport = $fin['0'];
$state = $fin['1'];
$distance= $fin['2'];
$price = $fin['3'];
$MsgWindow="Your estimate to $airport $state is $price";
echo $MsgWindow;
echo "<br>";
?>
<p>Click the button to write some text in the new window and the source (parent) window.</p>
<button onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction()
{
var myWindow = window.open("", "myWindow", "width=200, height=100");
// Change here
myWindow.document.write("<?php echo $MsgWindow; ?>");
myWindow.opener.document.write("<p>This is the source window!</p>");
}
</script>
</html>
myWindow.document.write('<?php echo $MsgWindow; ?>');myWindow.document.write("<?php echo $MsgWindow; ?>");?<?php>will give a PHP compilation error: remove the>.