How to pass two arguments in the JavaScript onclick function by programming in PHP?

1

I have a button that I generate with AJAX and on that same button it has an event onclick , and I want to pass two arguments to it, however I am having bugs with it.

PHP code:

 echo ' <button type="button" class="btn btn-link btn-comentario-reposta" id="botao-esconde-resposta-'.$_POST['id'].'"
            onclick="acao_botao_esconde_resposta('.$_POST['id'].','. $btn_mostrar_resposta .')">Esconder respostas</button>';

Here's what the Hide Answers button was for.

    
asked by anonymous 22.11.2017 / 21:22

2 answers

3

Your problem is that you failed to escape the '' of your arguments, correcting your code it looks like this:

echo ' <button type="button" class="btn btn-link btn-comentario-reposta" id="botao-esconde-resposta-'.$_POST['id'].'"
            onclick="acao_botao_esconde_resposta(\''.$_POST['id'].'\',\''. $btn_mostrar_resposta .'\')">Esconder respostas</button>';

How it works:

In order to escape some special character such as "" the quotation marks or '' simple quotation marks that we use to pass arguments inside the functions we use the \ backslash so that in the code it considers the character as part of the string, an example which can be better explained is the following:

$id = $_POST['id'];
$email = $_POST['email'];
$html = '<button id="btn-'.$id.'" onclick="func_teste('.$id.','.$email.')"></button>';
echo $html;

This would be your case where the error happens and why? Well when this code is for the html it will be generated this way for example:

<!-- código html -->
<button id="btn-1" onclick="func_teste(1,[email protected])"></button>
<!-- código html -->

As we can see, the parameter path is wrong and so your code is printing )">Esconder respostas to avoid this problem you have to put the \"\" quotation marks or \'\' single quotes to make your escape and thus they become literal .

$id = $_POST['id'];
$email = $_POST['email'];
$html = '<button id="btn-'.$id.'" onclick="func_teste(\''.$id.'\',\''.$email.'\')"></button>';
echo $html;

And the result will look like this:

<!-- código html -->
<button id="btn-1" onclick="func_teste('1','[email protected]')"></button>
<!-- código html -->
    
22.11.2017 / 21:31
1

Personally I think in your case it is simpler to write the html as html and put only what comes from php with <?=

<?php
$id = $_POST["id"];
?> 
<button type="button" class="btn btn-link btn-comentario-reposta" 
    id="botao-esconde-resposta-<?=$id?>"             
    onclick="acao_botao_esconde_resposta('<?=id?>','<?=$btn_mostrar_resposta?>')">
          Esconder respostas
</button>
    
22.11.2017 / 23:43