-2

Uncaught SyntaxError: Unexpected end of input

I have checked all the parenthesis and brackets but seems like nothing is missing.

while ($row = mysqli_fetch_array($query)) {
  echo '<div class="columns '.$row['type'].'">';
    echo '<div class="image" style="background-image: url(images/'.$row['image_tag'].')"></div>';
    echo '<div class="description">';
    echo '<p class="productName">'.$row['name'].'</p>';
    echo '<p class="productDetails">'.$row['details'].'</p>';
    echo '<p class="productPrice"> RM'.$row['price'].'</p>';
    //the line below cause error.
    echo '<button class="addItem" onclick="addToCart("'.$row['name'].'")">Add to cart</button>';
    echo "</div>";
    echo "</div>";
}
function addToCart(name){
      console.log(name);
    }
YKW
  • 25
  • 1
  • 6

2 Answers2

1

In my opinion you should change it from

echo '<button class="addItem" onclick="addToCart("'.$row['name'].'")">Add to cart</button>';

to

echo '<button class="addItem" onclick="addToCart(\''.$row['name'].'\')">Add to cart</button>';

Because $row['name'] returns a string value so it should be wrapped with single quotes (because double quote is used for element attribute definition) in order to pass it as a string value to javascript function.

mb.akturk
  • 301
  • 2
  • 7
  • 1
    Note that this will still break if `$row['name']` contains any quote. You must [escape all values correctly](https://stackoverflow.com/a/15892666/476). – deceze May 17 '19 at 07:19
  • @deceze escape all values correctly as in $name= sprintf(%s, json_encode($row['name')); ? – YKW May 17 '19 at 07:43
  • @YKW Yes. Ensure your PHP value has proper Javascript syntax with `json_encode`, then ensure that Javascript value has proper HTML syntax with `htmlspecialchars`. Though that specific `sprintf` call is invalid, I'll assume it's just symbolic in your comment. – deceze May 17 '19 at 07:43
-1

Try changing:

echo '<button class="addItem" onclick="addToCart("'.$row['name'].'")">Add to cart</button>';

To:

echo '<button class="addItem" '."onclick=\"addToCart('{$row['name']}')\"".'>Add to cart</button>';
medard mandane
  • 549
  • 4
  • 6