JavaScript echo warning about PHP array value on HTML button?

I am trying to use PHP to echo a set of buttons (buy and sell) in a stock market game. In the end, the buttons will have an onclick = event handler that calls the JavaScript function to populate some form fields, but I'm just trying to get a warning () with one piece of data to work with. I just can’t get the results from my echo instruction to print a warning correctly, so it doesn’t even start. I also used print_r ($ stockInfo) to make sure my array is correctly populated with test data.

Here is my array:

$stockInfo = array( array('name' => 'Company 1', 'description' => 'Description 1', 'price' => '100', 'yield' => '.05'), array('name' => 'Company 2', 'description' => 'Description 2', 'price' => '89', 'yield' => '.06'), array('name' => 'Company 3', 'description' => 'Description 3', 'price' => '110', 'yield' => '.03') ); 

And my PHP code that is trying to generate a button:

 <?php echo <<<EOT <button id="buy" class="btn btn-primary btn-small" onclick="alert('$stockInfo[0]["name"]');">Buy</button> EOT; ?> 

Result of this code:

 <button id="buy" class="btn btn-primary btn-small" onclick="alert('Array["name"]');">Buy</button> 

I just can't understand why I can't get even a simple warning for shooting. Duration:

 echo $stockInfo[0]["name"]; 

"Company 1" prints correctly, but it does not print this text in the alert () argument.

I read Stackoverflow, a lot of web articles and experimented on the last day, and I just can't figure it out. If anyone can provide any help, I would GREAT rate it.

Thanks!

+4
source share
3 answers

To use variables in the heredoc syntax , you must place curly braces around them:

 <?php echo <<<EOT <button id="buy" class="btn btn-primary btn-small" onclick="alert('{$stockInfo[0]["name"]}');">Buy</button> EOT; ?> 
+5
source

Ideally, you do not want to put variables directly in your output, because if there is only one in this line, your JavaScript will be corrupted.

Instead, avoid both problems by not using HEREDOC and using the appropriate method:

 echo "<button id=\"buy\" class=\"...\" onclick=\"alert(".htmlspecialchars(json_encode($stockInfo[0]['name'])).");\">Buy</button>"; 

json_encode essentially makes any PHP variable (except resources) that can be dumped directly into JavaScript code.

htmlspecialchars makes the result safe for use in the HTML attribute.

+1
source
 echo <<<EOT <button id="buy" class="btn btn-primary btn-small" onclick="alert({$stockInfo[0]["name"]});">Buy</button> EOT; ?> 
0
source

Source: https://habr.com/ru/post/1402320/


All Articles