pass php variable to a javascript onclick function as an argument

How to pass php variable value to a javascript onclick function as an argument?

here is my code:

echo ‘<li>’.$mainGroup->name.’<input type=“button” value="-remove" onclick=“removeMainGroup(’.$g->id.’);” ></li>’;

its not working.

anyone have a soluton for this?


What does it means that "its not working"? What happen? Where is javascript. What tell you firebug?

can you try this

echo '<li>.$mainGroup->name.<'input type="button" value="remove" id=".$g->id." ></li>

//in you jquery script 


      $('li button').click(function(){

              var remove =  $(this).attr('id');

      //pass to the ajax 





note that i have not tested it

I suspect your problem might be missing “” and as a result removeMainGroup isn’t sent the contents of $g->id but rather an undefined javascript variable with that name


echo '<li>' . $mainGroup->name . '<input type="button" value="-remove" onclick="removeMainGroup("' . $g->id . '");" ></li>';

I’d suggest using HEREDOC or simliar styles to do this, as it won’t break any " or ‘’(no need to escape static content) in HTML/Javascript(but requires PHP 5.3++)


<li>{$mainGroup->name}<input type="button" value="-remove" onclick="removeMainGroup("{$g->id}")></li>


never ever use the onClick feature… to start with…

and btw, the solution to your problem is only syntax stuff.

[color="#006400"]/* Moved to Yii 1.1 General Discussion as it’s not a tip, nor a snippet or even a tutorial… */[/color]