user1234 user1234 - 27 days ago 5
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

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

function viewMessage(id){


Its gives me 1 in alert but i want to use
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
it is breaking like this

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

$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


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>';  


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