Reputation: 315
I already tried all the methods i saw here in Stackoverflow but im getting errors.
Im trying to pass a php variable value to a javascript function, im trying to do both methods:
echo '<td><a href="#" onclick="delete('.$contact['idContact'].')"> Delete </a></td>';
This method above thinks the value of the idContact is actually a variable, so he is trying to get the value of the variable "105" (the value of idContact)
echo '<td><a href="#" onclick="delete("'.$contact['idContact'].'")"> Delete </a></td>';
This method gives me
Uncaught SyntaxError: Unexpected token }
What is the correct way to do it? Thanks in advance.
Here is a simple code to show my problem:
<html>
<head>
<script>
function eliminate(test)
{
alert(test);
}
</script>
</head>
<?
$test = "name";
echo '<a href="#" onclick="eliminate('.$test.')"> Delete </a>';
?>
</html>
Upvotes: 1
Views: 13859
Reputation: 87
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
function eliminate(test){
alert(test);
}
<script>
</head>
<body>
<?php $test="name"; ?>
<a href="" onclick="eliminate('<?php echo $test; ?>')">delete</a>
</body>
</html>
Upvotes: 1
Reputation: 2320
to avoid confusion use heredoc for this
$button=<<<HTML
<a href="#" onclick="eliminate('$test')"> Delete </a>
HTML;
echo $button
Also remeber if you are using json as paramter make sure to escape them properly or it will not work
Upvotes: 0
Reputation:
gotta quote it if it's a string or else js will assume it's a variable
echo '<td><a href="#" onclick="delete(\''.$contact['idContact'].'\')"> Delete </a></td>';
note the escaped quotes on either side \'
a better way of passing variable from php to js is to json encode them, that will take care of quotes and things...
Upvotes: 2