user1234 user1234 - 2 months ago 7
HTML Question

php variable inside onclick function?

I have a php file in this i have to write html also instead of closing php tag every time i just use

echo 'html code';


So my code is like

<?php
$mid = 1;
echo '<div class="message_wrap"><span onclick="viewMessage(1)">Click</span></div>';
?>

<script>
function viewMessage(id){
alert(id);

}
</script>


Its gives me 1 in alert but i want to use
$mid
in
onclick function
but it breaks my code i used this

echo '<div class="message_wrap"><span onclick="viewMessage("'.$mid.'")">Click</span></div>';


but I got nothing on clicking and when i see generated
html
it is breaking like this

<div class="message_wrap"> <span 1")"="" onclick="viewMessage(">Click</span> </div>
;

<?php
$mid = 1;
?>
<div class="message_wrap"><span onclick="viewMessage(<?php echo $mid;?>)">Click</span></div>


But i don't want to close and open php tag as i have large code so it is not looks good.

Please help me to get it works

Answer

It returns "Uncaught SyntaxError: Unexpected token }" error because the parameter you passed has space before it and "="" after ) because of that approach

to fix it change your

echo '<div class="message_wrap"><span onclick="viewMessage("'.$mid.'")">Click</span></div>';  

to

echo '<div class="message_wrap"><span onclick="viewMessage(\''.$mid.'\')">Click</span></div>';
Comments