简体   繁体   中英

passing php variable in onClick function

I want to pass the php variable value in onClick function. When i pass the php variable, in the UI i am getting the variable itself instead I need the value in the variable.

Below is code snippet, please help me.

<?php
print '<td>'; 
$node  = $name->item(0)->nodeValue;
$insert= "cubicle"."$node<br>";
Echo '<a href= "#" onClick= showDetails("$node");>'. $insert .'</a> ';
print '</td>';
?>

Variable parsing is only done in double quoted strings . You can use string concatenation or, what I find more readable, printf [docs] :

printf('<a href= "#" onClick="showDetails(\'%s\');">%s</a> ', $node, $insert);

The best way would be to not echo HTML at all, but to embed PHP in HTML:

<?php
    $node  = $name->item(0)->nodeValue;
    $insert = "cubicle" . $node;
?>

<td> 
    <a href= "#" onClick="showDetails('<?php echo $node;?>');">
        <?php echo $insert; ?> <br />
    </a>
</td>

You have to think less about quotes and debugging your HTML is easier too.

Note: If $node is representing a number, you don't need quotations marks around the argument.

you shouldn't be wrapping $node in '"':

Echo '<a href= "#" onClick= showDetails($node);>'. $insert .'</a> ';

If you want the value of $node to be in a string, thn i would do:

Echo '<a href= "#" onClick= showDetails("' . $node. '");>'. $insert .'</a> ';

I have been using curly braces lately instead of concatenation. I think it looks better/is more readable, and mostly I find it is easier and less prone to human error - keeping all those quotes straight. You will also need quotes around the contents inside of onClick.

Instead of this:

Echo '<a href= "#" onClick= showDetails($node);>'. $insert .'</a> ';

Try this:

Echo '<a href= "#" onClick= "showDetails({$node});">{$insert}</a> ';

As a side note, I usually use double quotes to wrap my echo statement and strictly use single quotes within it. That is just my style though. However you do it, be sure to keep it straight. So my version would look like this:

echo "<a href='#' onClick='showDetails({$node});'>{$insert}</a>";
$var = "Hello World!";
echo "$var"; // echoes Hello World!
echo '$var'; // echoes $var

Don't mix up " and ' , they both have importance. If you use some " in your string and don't want to use the same character as delimiter, use this trick:

echo 'I say "Hello" to ' . $name . '!';
Echo '<a href= "#" onClick= showDetails("'.$node.'");>'. $insert .'</a> ';

I think you are searching for PHP function json_encode which converts PHP variable into JavaScript object.

It's more secure than passing the value right in the output.

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