List of products displayed from database using PHP. When product selected javascript function called to enter product into HMTL form field.
<div id="addProductPanel">
<div class="popularProduct">Popular products</div>
<div class="closeButton" onclick="closePopularProductWindow()">X</div>
<?php
$query_popular_product="SELECT product_code FROM database_table GROUP BY product_code ORDER BY product_code DESC";
$result_popular_product = $link->query($query_popular_product);
while($row = $result_popular_product->fetch_assoc()) {
$product_code = $row['product_code'];
echo '<div onclick="setProduct("'.$product_code.'")">'.$product_code.'</div>';
}
?>
</div>
The js function setProduct is:
function setProduct(product) {
console.log(product);
document.getElementsByName("product")[0].value = product;
document.getElementById("addProductPanel").style.display = "none";
}
When loading the page and using Chrome inspector console, selecting a product doesn't print the product in the console and produces the error Uncaught SyntaxError: Unexpected end of input
with HTML displayed as below:
<div class="popularProduct" onclick="setProduct("PROD123")">PROD123</div>
I have tried typing the following HTML and this works successfully with the javascript function:
<div class="popularProduct" onclick="setProduct('PROD123')">PROD123</div>
Cannot get the PHP syntax working with the product values from the database.
CodePudding user response:
Use single quotes instead of double quotes:
echo '<div onclick="setProduct(\''.$product_code.'\')">'.$product_code.'</div>';
The double quotes will terminate the double quotes from onclick="setProduct(...
(Single quotes inside single quotes need to be escaped, so use \'
)