Saurabh Saurabh - 22 days ago 5
Ajax Question

How to hide a dropdown list provided the data is filled by ajax

I have made a simple dropdown list in which the data is filled by the ajax call.

Here is the code(for simplicity,I am just sharing the body content of the html page):

<body>
<div class="dropdown">
<span id ="id-wala" class="glyphicon glyphicon-th-large btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
</span>
<span id="notification_count"></span>
<ul id ="fill_list" class="dropdown-menu" aria-labelledby="id-wala">
</ul>
</div>
<script type="text/javascript">
$("#id-wala").click(function(){
/*$("#id-wala").click(function(){
$("#id-wala").addClass("selected");
});*/
//$("#id-wala").next('ul#fill_list').hide();
$.ajax({
type:"GET",
url:"notification_list.php",
beforeSend: function(html) {
$("#fill_list").html('');
//$("#jk").show();
},
success: function(html){
$("#fill_list").show();
$("#fill_list").append(html);
}
});
});
</script>
</body>


On clicking the dropdown icon,the click event is fired and a get request is made to notification_list.php,it correctly echoes the data which is then showed on the html page.

The problem is that when I click the dropdown icon again,the list doesn't disappears.Maybe it's because of the click event,I tried to attach some events within the click event(commented in the code) to remove the dropdown list but they don't seem to work.

Can anyone please suggest how to add another event to remove this list?

Answer

It's because you are manually showing the dropdown when the AJAX comes back:

success: function(html){
  $("#fill_list").show();
...

Bootstrap JavaScript already handles hiding/showing, you don't need to do it.

Another problem is that you are doing AJAX calls on both opening and closing the dropdown. You should probably do it on opening only.