Call a JavaScript function (with parameters) using the onclick event

I cannot use PHP variables to use as parameters for my function.

Function:

<script type="text/javascript"> function myFunction(id,name) { alert(id); alert(name); } </script> 

And this is part of PHP:

 echo "<button onclick='myFunction($intvar,$strvar)' type='button'>ClickMe</button>"; 

the call works when I use numbers like this: myFunction (0,1) but I need to use variables to call myFunction.

Please help, thanks.

+5
source share
2 answers

You will try this function myFunction(ide,name) { change insted id => ide echo "<button onclick='myFunction(".'"'.$intvar.'","'.$strvar.'"'.")' type='button'>ClickMe</button>";

+3
source

A good practice is to echo the json version of the variables, so you guarantee that the lines are quoted correctly:

 echo "<button onclick='myFunction(" . json_encode($intvar) . "," . json_encode($strvar, JSON_HEX_APOS) . ")' type='button'>ClickMe</button>"; 
+5
source

All Articles