Call JavaScript function(with parameters) by onclick event

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

The function is:

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

And this is PHP part:

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.

Upvotes: 6

Views: 3957

Answers (2)

dfsq
dfsq

Reputation: 193261

Good practice is to echo json encoded version of variables, this way you ensure that strings are properly quoted:

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

Upvotes: 5

Ambal Mani
Ambal Mani

Reputation: 315

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

Upvotes: 6

Related Questions