Cannot get list item id using jQuery

I need to pass the list item id to ajax, and this code doesn't seem to do the job:

HTML:

    <ul  id="tree">
       <li><a id="1">Finance</a></li>
       <li><a id="2">ACC</a></li>
        <li><a href="<?php echo base_url()?>admincont/departament/6>">HR</a></li>
   </ul>

JavaScript:

<script type="text/javascript">
$( document ).ready(function() {
  $('#tree li').click(function(){
    $.ajax({
       method: "POST",
       data: {depID: $(this).attr('id')},// i have also tried  $(this).id
      url: "<?php echo base_url();?>/assets/getdepartment.php",
      success: function(msg){
        $('#result').html(msg);
      }
    })
  })
});
</script>

My php file:

<?php
$depID = $_POST['depID'];
echo $depID;
?>

In my div result, I get "Note: Undefined index: depID on line 2"

+4
source share
1 answer

this does not apply to your anchor, it refers to a list item.

You can find the anchor using thisthough:

data: {depID: $(this).find('a').attr('id')}

Or (preferably, in my opinion), just attach an event handler to the anchor:

$('#tree li a').click(function(e){
    e.preventDefault(); // If you need to prevent the default behaviour
    $.ajax({
        method: "POST",
        data: {depID: $(this).attr('id')},
        url: "<?php echo base_url();?>/assets/getdepartment.php",
        success: function(msg){
            $('#result').html(msg);
       }
   })
})
+5
source

Source: https://habr.com/ru/post/1615098/


All Articles