Adrian
Adrian

Reputation: 315

Pass PHP variable on OnClick method

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

Answers (3)

<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

ahhmarr
ahhmarr

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

user6534863
user6534863

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

Related Questions