6

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.

1
  • 2
    change alert(ide); to alert(id); Jun 25, 2015 at 6:19

2 Answers 2

6

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

0
5

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>";
3
  • It will if you provide a flag JSON_HEX_APOS.
    – dfsq
    Jun 25, 2015 at 6:29
  • I try with json_encode and works too, thanks too much. Jun 25, 2015 at 6:32
  • But now if double quotes are used for the attribute.. sigh. The problem is there is not (nor has there been) a good way to supply values as JavaScript arguments in attributes. So much for being a[n HTML] 'template' language .. Jun 25, 2015 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.