Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Populating bootstrap dropdown with ajax

I currently have a dropdown that will display notifications

<li class="notifications dropdown"> 
  <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifications"><i class="icon-user"></i> Notifications</a>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
  </ul>
</li>

The ul dropdown is empty but on click of the link I want to populate the menu with data from rails.

I currently have this in notifications.js.erb

$(".nav li.notifications .dropdown-menu").remove();
$(".nav li.notifications").append("<%= escape_javascript(render('users/notifications', notifications: @notifications)) %>");

Normally I would set the dropdown link to remote but since I am using a bootstrap's dropdown no request is being sent to notifications.js.erb. How can I manually call the code there?

like image 941
Matthew Hui Avatar asked Oct 14 '12 18:10

Matthew Hui


1 Answers

I would add JavaScript code to make the call:

$(document).ready(function() {
    $('#dLabel').click(function() {
        // Only call notifications when opening the dropdown
        if(!$(this).hasClass('open')) {
           $.ajax({
              type: "GET",
              url: "/notifications",
              async: false,
              dataType: "script"
           });
        }
    });
});

You could also make it asynchronous and put a loading icon into the menu temporarily...

like image 186
mccannf Avatar answered Nov 04 '22 14:11

mccannf