Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>';
?>
like image 518
Vinod HC Avatar asked Jul 08 '11 07:07

Vinod HC


People also ask

Can we pass parameter in onClick function?

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...

Can I use onClick in PHP?

Can I use onclick in PHP? Wrong Interpretation of Onclick Event in PHP In addition to that, PHP handles server-side client requests and database connections. PHP has nothing to relate to the user side, on-screen interaction. So, we can not set an on click event of client-side javascript with a PHP function.

How set PHP variable in JavaScript?

To Set PHP Variable in JavaScript, we define a JS variable and assign PHP value using PHP tag with single or double quotes. Most of the time you have to set PHP variable value in JavaScript. If there is only simple variable like string or any integer then you can simply echo on the JS variable with PHP tag.


2 Answers

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.

like image 90
Felix Kling Avatar answered Sep 19 '22 12:09

Felix Kling


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> ';
like image 26
Jim Deville Avatar answered Sep 20 '22 12:09

Jim Deville