After click on button some Javascript alerts are displayed and some aren't. Why?

Viewed 43

A webpage displays all records from the database table motocykle to special container.

It looks like this:

enter image description here

Code

<div class="dbmaincontainer">
  <div class="finddbspecificcontainer">
    <div class="finddbimgcontainer">
    <?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['img'] ).'"  />';?>
    </div>

    <div class="finddbspecificvalues">
      <div class="findvalue1">
        <label class="blackbold600">MARKA: </label>
        <?php echo $row['mark'];?>
      </div>
      <div class="findvalue1">
        <label class="blackbold600">MODEL: </label>
        <?php echo $row['model'];?>
      </div>
      <div class="findvalue1">
        <label class="blackbold600">POJEMNOŚĆ: </label>
        <?php echo $row['capacity'];?>
        <label class="blackbold600"> CC</label>
      </div>
      <div class="findvalue1">
        <label class="blackbold600">MOC: </label>
        <?php echo $row['power'];?>
        <label class="blackbold600"> KM</label>
      </div>
    </div>

    <div class="finddbbutton">
      <button class="button" onclick="alert('<?php echo $row['description'];?>');">Pokaz Opis</button>
    </div>
  </div>
</div>

Problem

After clicking the button "Pokaz opis" some alerts are displaying, and some aren't. Where is the problem?

2 Answers

If any of the descriptions contain quotes, substituting it into the HTML will cause errors because those quotes will terminate either the onclick attribute or the string argument to alert(). You need to encode the quotes to prevent this, this can be done using htmlentities().

   <button class="button" onclick="alert('<?php echo htmlentities($row['description'], ENT_QUOTES);?>');">Pokaz Opis</button>

Tray this. I always use for output htmlspecialchars when it's not id. When this is id urlencode with htmlspecialchars.

function h($string="") {
  return htmlspecialchars($string);
}

<button class="button" onclick="alert('<?php echo h($row['description']); ?>');">Pokaz Opis</button>
Related