Reputation: 63
i have a auto suggest textbox witch generates li tags with a onclick event with a function but i have to pass a php variable to the function as parameter but i only want the variable value of the li the user clicked on and now i always get the last variable in the loop. And i want the var test to be the value of $test = $row['t_product']; of the li the user clicks on
here is the code im using now:
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
$search_term = $_POST['search_term'];
$customerid = $_SESSION['userdata']['t_customer_id'];
$conn = connect();
$sql = "SELECT * FROM Licenses WHERE customer_id = '$customerid' AND t_name LIKE '$search_term%'";
$query = sqlsrv_query($conn, $sql);
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<script type="text/javascript">
var test = <?php echo json_encode($test); ?>;
</script>
<?php
echo '<li onclick="show(test)">', $row['t_name'], '</li>';
}
}
i hope i explained my problem well and hope that some wane can help me :)
Upvotes: 1
Views: 610
Reputation: 63
solved it by passing the $test value as id to each li and in the js get it with
$test = $row['t_product'];
echo '<li onclick="show(this)" id="'.$test.'">', $row['t_name'], '</li>'
function show(id){
alert($(id).attr("id"));}
Upvotes: 0
Reputation: 61
Well, maybe you should do :
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<?php
echo '<li onclick="show("'.$test.'")">', $row['t_name'], '</li>';
}
or
if(isset($_POST['search_term']) == true && empty($_POST['search_term']) == false){
$index = 0;
$search_term = $_POST['search_term'];
$customerid = $_SESSION['userdata']['t_customer_id'];
$conn = connect();
$sql = "SELECT * FROM Licenses WHERE customer_id = '$customerid' AND t_name LIKE '$search_term%'";
$query = sqlsrv_query($conn, $sql);
while(($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) != false){
$test = $row['t_product'];
?>
<script type="text/javascript">
var test<?php echo $index++ ?> = "<?php echo $test; ?>";
</script>
<?php
echo '<li onclick="show(test'.$index++.')">', $row['t_name'], '</li>';
}
}
Edit: removed json_encode and replaced it with quotes
Upvotes: 1