Concatenate Javascript with PHP

Asked

Viewed 499 times

2

I’m trying to concatenate PHP with Javascript, but I’m not getting it.

<button onclick="gravaDados('/" . <?php echo nomeCliente; ?> . /"')" class="btn-playpause">Play</button>

Thank you

3 answers

3

Here we go:

<button onclick="gravaDados('<?= $nomeCliente; ?>')" class="btn-playpause">Play</button>

The tags <?= ?> want to say the same thing <?php echo ...; ?>.

Difference between php <?php tags and <?=

On second thought, you don’t need counterbars. Use only the simple quotes, you will get the result you search.

If your Apache or IIS, CGI, has not enabled the permission or use of short PHP tags, you can use:

<button onclick="gravaDados('<?php echo $nomeCliente; ?>')" class="btn-playpause">Play</button>

Don’t forget to use $ before the variable name to indicate variables in PHP.

  • You’re in charge, @Andersoncarloswoss!

  • 1

    I’m sorry, but my answer was given. I don’t need an academic essay to answer such a simple question. The default settings of PHP yes, allow that from version 5.4 the tags in this form are used, but due to problems with XML, some servers disable its use in Apache.

  • @Andersoncarloswoss All right but not all the server has the most updated version of php still exist hosting with php 5.3 which is 3 times slower than php 7

1

Another alternative might be to use printf (or sprintf depending on the case):

printf('<button onclick="gravaDados(\'%s\')" class="btn-playpause">Play</button>', $nomeCliente);

I don’t think it’s the best option, but it’s another option.


Depending on the context I believe it is appropriate to encode the HTML of $nomeCliente to mitigate XSS, in this case something like:

printf('<button onclick="gravaDados(\'%s\')" class="btn-playpause">Play</button>',
htmlentities($nomeCliente, ENT_QUOTES | ENT_HTML5, 'UTF-8'));

Without using the htmlentities, the way the other answers did, if the value of the $nomeCliente for );alert('XSS will inject an alert (or any other malicious code the user obviously wants) into the website, see here.

0

The problem is that you don’t need to escape the quotes even because to space them is with \ and at the same time are concatenating outside the PHP

Enough like this:

<button onclick="return gravaDados('<?php echo $nomeCliente; ?>');" class="btn-playpause">Play</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.