kamran kiani
kamran kiani

Reputation: 53

a javascript fuction doesn't execute when i echo that in php code

I want to echo the following html code on my page. But the onclick event doesn't work when I do this. the $senduser has the correct value

$table1="<div id='sendmsg' class='row'>
<div class='col-lg-6'>
<textarea id='msg' cols='40' placeholder='Write your message here...'></textarea>
</div><div class='col-lg-2' >
<button type='button' onClick='sendmsg(".$senduser.")' class='btn btn-success' value='send' id='msgbtn'>Send to</button></div></div>";

echo $table1;

my javascript function:

function sendmsg(senduser){
  alert(senduser);
  .
  .
  .
}

Alert doesn't show anything.

Upvotes: 1

Views: 63

Answers (3)

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

Try this

<?php 
$senduser = '1';
$table1="<div id='sendmsg' class='row'>
<div class='col-lg-6'>
<textarea id='msg' cols='40' placeholder='Write your message here...'></textarea>
</div><div class='col-lg-2' >
<button type='button' onClick='sendmsg(".$senduser.")' class='btn btn-success' value='send' id='msgbtn'>Send to</button></div></div>";

echo $table1; ?>

<script>
function sendmsg(senduser){
  alert(senduser); 
}
</script>

Upvotes: 0

Jamie Hutber
Jamie Hutber

Reputation: 28076

Make sure you're wrapped the javaScript in a script tag

<script>
   function sendmsg(senduser){
          alert(senduser);
          .
          .
          .
    }
</script>

Upvotes: 0

jeroen
jeroen

Reputation: 91734

$senduser is probably a string and as you don't quote it, it is interpreted as a (undefined...) variable in javascript.

You need to quote it:

...
<button type='button' onClick='sendmsg(\"".$senduser."\")' class='btn btn-success' ...
 //                                    ^^ here        ^^ and here

Upvotes: 1

Related Questions