I have a .PHP file and wanted to echo HTML. I did echo it perfectly but now i want to echo a javascript onclick= print( $variable) . I keep getting error or invalid syntax.
the button on click won't work when i pass in a php variable but if i pass in manually it works.
Thank you.
Below are my code.
<div class="streamline b-l m-l">
<?php
$messages = $user_projects_json['projects'][$projectKey]['alarms'];
foreach($messages as $message_key => $messagesList){
echo "
<div class='sl-item b-success'>
<div class='sl-icon'>
<i class='fa fa-check'></i>
</div>
<div class='sl-item b-info'>
<div class='sl-content'>
<div class='sl-date text-muted'>". $messagesList['t'] ."
<span class='pull-right'>Name: " . strtoUpper($messagesList['n']) . " </span>
</div>
<div> " .$messagesList['m'].
"<span>
<button onclick='clear_alarm(" . $message_key . ")' class='btn btn-sm white pull-right'> Clear </span> </button> </div>
<div>
</div>
</div>";
}
?>
</div>
1 Answer 1
If $message_key is a string, you need to put quotes around it.
<button onclick='clear_alarm(\"" . $message_key . "\")' class='btn btn-sm white pull-right'> Clear </span> </button> </div>
answered Jul 28, 2020 at 21:42
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Dennis Ong
Thank you so much! What is the backslash for actually?
Taplar
@DennisOng It's the escape character, to make the double quote be treated as a literal.
var x = "\""; or var x = '\''; as different examples. That's javascript but the same syntax works in PHP as well, iirc.Barmar
If you don't escape the double quote, it will end the PHP string instead of being put into the string. @DennisOng
Dennis Ong
Oh, what if i have two variables in the functions?
Barmar
Put quotes around each of them, and separate them with commas.
clear_alarm(\"" . $var1 . "\", \"" . $var2 . "\") |
default
". If the value of$message_keyis a string, your source is going to look likeonclick='clear_alarm(mystringvalue)'. In which case javascript is going to treat that string as a variable reference, not a literal.