user7166543 user7166543 - 18 days ago 5
PHP Question

Pass the value when a <div> has onclick function and the data inside is changing dynamically

enter image description hereThis is my index_category.php.

<?php
include("db.php");
$sql="SELECT * from tcategory";
$conect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($conect, MYSQLI_ASSOC)){ ?>
<div class="dialog-outer" data="<?php echo $rows['cat_id']; ?>" onclick="openNav()">
<div class="dialog-inner">
<?php echo $rows['cat_nm'];?>
</div>
</div>
<?php }
?>


This is the side nav to which I want to pass the data of div

<div id="mySidenav" class="sidenav">
<h3 class="sub"><i class="fa fa-arrow-right" aria-hidden="true"></i><strong> Sub Category</strong></h3>
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<div id="result">
<?php include("functions/sub_category.php")?>
</div>
</div>

<script>
function openNav() {
$("#mySidenav").attr("style","width:250px");
var id=$(".dialog-outer").attr("data");
alert(id);
$.post('functions/sub_category.php',{id: id},function(data){
$('#result').html(data);
});
}

function closeNav() {
$("#mySidenav").attr("style","width:0px");
}
</script>


The problem is it is taking
data=1
only but in network it showing as
data=1 data=2 data=3 so on...

How to pass all the values from div in
index_category.php
to script in
index.php


as u can see in the image i want to filter the sub category based on category. But when i click on any of the category it is taking only first value.But when u look in the image(inspect element) it is taking all the values as data=1 data=2 so on...when i click on category i want to get their respective id's.

Answer

If I understand correctly your your outer nav is repeated, that means that your $(".outer-nav") will return an array of elements not just one. You will need to iterate over them to read their data attributes. If you are looking to get just one specific one I would recommend using JQuery(since you are using it) selector for the click detection and from there working out the .outer-nav that you need.

Sorry if I did not understand your question correctly, but you use a weird mixture of pure JS and JQuery so it is a bit stange to read the code.

Comments