Passing php variable in onClick function

I want to pass the value of php variable in onClick function. When I pass the php variable, in the user interface I get a variable instead of me, I need a value in the variable.

Below is a snippet of code, 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>'; ?> 
+7
source share
5 answers

Variable parsing is performed only in double quotes . 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 not echo HTML at all, but 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 need to think less about quotes and debugging your HTML code is easier.

Note. If $node represents a number, you don't need quotation marks around the argument.

+14
source

you should not wrap $ node in '"':

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

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

 Echo '<a href= "#" onClick= showDetails("' . $node. '");>'. $insert .'</a> '; 
+4
source
 $var = "Hello World!"; echo "$var"; // echoes Hello World! echo '$var'; // echoes $var 

Do not mix " and ' , they both matter. If you use some " in your string and don’t want to use the same character as the delimiter, use this trick:

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

I think you are looking for a PHP function json_encode that converts a PHP variable into a JavaScript object.

This is safer than passing the value to the right of the output.

0
source

All Articles