I want to pass two values ​​to the function by clicking on the link, I do this:

onclick="gov('.$id.', "info") 

When clicking, I get an error in the chrome console: Uncaught ReferenceError: info is not defined at HTMLAnchorElement.onclick

Function: function gov(id, type) { ... }

at transfer of one value everything works. What could be the problem?

UPD. I noticed that if the second value is a digit, everything works, but there is no text.

  • 2
    Stop using on... attributes. Highly recommended - tutankhamun
  • Look like it’s okay, try wrapping 'info' in single quotes - yolosora
  • @yolosora cannot be set to single because it is a link in echo '<a ...>'; - iKey
  • @ Denis screen them - tutankhamun

2 answers 2

Depending on what info . If it's just a string, then you have to write either

 onclick="gov('.$id.', 'info')" 

either escape double quotes

 onclick="gov('.$id.', \"info\")" 

single cannot be, because this is a link in echo '<a ...>' ;

So you need to work with escaping inside the output line in PHP:

 <?php $id = 10; echo '<a href="#" onclick="gov('.$id.', \'infoHello\')">click me</a>' ?> <script> function gov(id, type) { alert(id + ', ' + type); } </script> 
  • info is just a string, a word. did not help (( - iKey
  • don't believe jsfiddle.net/vupf3zuk - creative me
  • @Denis looked at the comment in question. Added in response. In general, it all comes down to shielding. If not in JS, then in PHP. We must always remember this, if we draw a lot of quotes in the string - creative me

So do not do

 echo '<a href="" onclick="gov('.$id.', \'info\')">'; 

Since you have jQuery, you can do this, for example:

 $params = htmlspecialchars(json_encode(array('id' => $id, 'type' => 'info'))); echo '<a href="" data-params="' . $params . '">'; 

Next to <script>

 $('[data-params]').on('click', function(e) { var params = $(this).data('params'); gov(params.id, params.type); }