开发者

How To Pass a PHP Variable To Javascript [duplicate]

This question already has answers here: How do I pass variables and data from PHP to JavaScript? (19 answers) Closed 8 years ago.
<html>
<head>
<?php
$your_name=$_POST['name'];
?>
<scrip开发者_StackOverflowt language="javascript">
function fash(at1,at2)
{
    alert(at1+at2);
}
</script>
</head>
<body>
<?php
echo $your_name;
echo '<script language="javascript">fash("the key is: "+'<?php echo $your_name; ?>');</script>';
?>
</body>
</html>

The output is:

the key is : undefined

How can I fix this?


This can't be the right code, it has syntax errors (e.g. you have a <?php block inside another <?php block). Probably the line that outputs a script tag is supposed to look like this:

echo "<script language=\"javascript\">fash(\"the key is: $your_name\");</script>";

Or like this:

?>
<script language="javascript">fash("the key is: <?php echo $your_name; ?>");</script>
<?php

That will get it to output "the key is: testnameundefined" (if $your_name is testname). The undefined comes from you defining fash to take two arguments and concatenate them, but you only passing one; at2 is undefined


It's hard to see what´s going on with all the editing, but it seems you are using <?php ?> tags when you are already inside php tags.

Just echoing and removing the inner <?php ?> should solve part of your problem, although it seems that your javascript function wants 2 paramenters as well instead of one (the text given).


You're passing only one parameter into your function:

fash("the key is: "+'php_value');

"the key is: " and your php string are concatenated before the function is called.

Try

fash("the key is: ", 'php_value');

instead.


The function fash takes two parameters. You are only passing one.

Use:

fash("the key is: ", "$your_name");

This will correctly display the alert after it concatenates these two strings. You do not need the PHP tags here because you are already in a PHP code block.


Because in your definition of fash, you take two parameters and concatenate them there, but in your echoed script, you concatenate them there and so only pass one parameter. So at2 is passed as undefined. Clearly your name is also blank.


echo '<script language="javascript">fash("the key is: "+'<?php echo $your_name; ?>');</script>';

It looks like you're echo'ing php code inside a php echo. Try changing it to:

echo '<script language="javascript">fash("the key is: "+'$your_name;');</script>';

Not sure if that solves the entire problem but I'm pretty sure you can't echo a new echo inside an echo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜