Así es como se muestran mis anclas en la web. Necesito obtener el valor del ancla y enviarlo a otro archivo PHP, así que usaría el valor del ancla en mi consulta SQL para dar la condición de mostrar todo el ID de producto asociado con el valor del ancla.
<?php include"validations/connection.php"; $sql = "SELECT * from category ORDER BY CHAR_LENGTH(categoryName)"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo' <div class="col-sm-12"> <ul class="nav flex-column"> '; while($row = $result->fetch_assoc()){ $id = $row['categoryId']; $sqltwo = "SELECT COUNT(productId) AS num FROM products WHERE categoryId = '$id'"; $resultwo = $conn->query($sqltwo); while($rowtwo = $resultwo->fetch_assoc()){ echo' <li class="nav-item"> <button value="'.$row['categoryId'].'" class="link-show">'.$row['categoryName'].'</button> <span class="badge badge-danger ml-1">'.$rowtwo['num'].'</span> </li> '; } } echo' </ul><hr> </div> '; } ?>Y aquí está mi JavaScript
<script> var id = document.querySelectorAll('.link-show').value; document.querySelectorAll('.link-show').forEach(item => { item.addEventListener('click', event => { var xhr = new XMLHttpRequest(); xhr.open('GET','validations/retrievebycategory.php?id='+id, true); xhr.onload = function(){ console.log(this.responseText); } xhr.send(); }) }) </script> // Remove this, it's querying all links // var id = document.querySelectorAll('.link-show').value; document.querySelectorAll('.link-show').forEach(item => { item.addEventListener('click', event => { // In the event handler, "this" is set to event.currentTarget (the button, in this case). // Equivalent formulations: // let id = event.currentTarget.value; // (from event, standard behavior, equivalent to "this") // let id = event.target.value // (from event's initial target, equivalent in most cases, except if the "click" is generated by a nested element; generally unsafe to use unless the intent is clear) // let id = item.value; // (from closure) let id = this.value; var xhr = new XMLHttpRequest(); xhr.open('GET','validations/retrievebycategory.php?id='+id, true); xhr.onload = function(){ console.log(this.responseText); } xhr.send(); }) })Ver modificaciones y explicaciones en el código