Reputation: 61
I need to pass list element 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 result div, i get "Notice: Undefined index: depID in line 2"
Upvotes: 4
Views: 56
Reputation: 36794
this
doesn't refer to your anchor, it refers to the list item.
You can find the anchor using this
though:
data: {depID: $(this).find('a').attr('id')}
Or (preferable, in my opinion), simply attach the event handler to the anchor instead:
$('#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);
}
})
})
Upvotes: 5