Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying 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>

Although the ul list inside the dropdown menu is currently empty, the intention is to populate it with Rails data upon clicking the link.

The logic for this action lies within notifications.js.erb:

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

The challenge here is that typically the dropdown link would be set to remote, but due to the implementation of Bootstrap's dropdown functionality, no request is being made to notifications.js.erb. The question then becomes how can we manually trigger the code execution from there?

Answer №1

To trigger the call, I suggest incorporating some JavaScript code:

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

You can also enhance it by using asynchronous loading and displaying a temporary loading icon within the menu...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...

Utilize PHP to populate grouped tables and filter them using jQuery through AJAX with JSON

There are two PHP files in play here. The first one, fetch.php, creates a filtered array (filtered from leagueboxes.php) and then sends it back to leagueboxes.php via Ajax JSON. fetch.php <?php include_once 'dbconfig.php'; if(isset($_GET[ ...

Sending a JSonArray to a Spring controller can be achieved by making use of

How can I send a jsonArray using an Ajax call to the Spring controller? [{"REQUEST_ID":"BBBBBBB","MATCH_COUNT":"Accountant","CLIENT_ID":"Tokyo","MATCH_REASON":"63","NAME":"2011/07/25","FATHER_NAME":"$170,750"},{"REQUEST_ID":"CCCCCCC","MATCH_COUNT":"Junior ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

Bootstrap 4 - positioning link element to align with heading in card header

I'm currently utilizing Bootstrap 4+ to design a card that features a collapsible card-body, triggered by a link located in the card-header. <div class="card text-left mb-3 mt-3"> <div class="card-header p-3"> <h4>Where should ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Having issues with npm python-shell integration within electron framework

I'm currently attempting to establish a connection between a python script and an Electron app by utilizing the npm's python-shell package. The requirement is for the script to be executed whenever a button is clicked. So, let's assume my d ...

Learning how to interpret data within configuration files (.properties) using JavaScript

I'm trying to retrieve data from a configuration file (.properties) in my code. The structure of my configuration file is as follows: maxTime = 60 upVotePostMaxTime=60 However, I am unsure of how to read this configuration file using JavaScript. Is ...

Setting up a project with Angular 2 and NodeJS

Hello there, I have some inquiries about organizing the project structure of a MEAN application with Angular2. Initially, I followed the introductory guide on angular.io to create a basic Angular2 app. Now, I am attempting to incorporate this app into a N ...

JavaScript - Capture user input and store it in a cookie when the input field is changed

Any help with my issue would be greatly appreciated. I'm currently working on saving the value of a form input type="text" to a cookie when the input has changed. It seems like I'm close to getting it right, but unfortunately, it's not worki ...

Learn how to dynamically incorporate multiple Bootstrap collapse elements in PHP

I've encountered an issue with my code that contains both HTML and PHP. The problem arises when there are multiple elements in a collapse, as only the first element works properly. This is due to the fact that each element has the same id named "colla ...

What is the best way to accurately establish a new name for the evolving scope

var tags_offset=[]; $scope.getRelations = function(id, ref, subRef=0){ tags_offset[ref+'-'+subRef]=0; $http.get( CONS.appHttp+ '/tags.php?ID='+id +'&ref='+ref +'&contentType='+subRe ...

JavaScript Tutorial: Extracting the text content of a drop event

Curious about extracting the text value from a drop event, I set out to find an answer. To my surprise, I discovered that it's not as straightforward as I thought. Check out the demo below: <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

jQuery - Event cannot be triggered on the 'deselect' or 'focusout' of <option> tag

Check out the demo here Hello there, I have a situation where I need an input box to appear below a select option, only if the user selects "Other". The code currently uses the .click() function on the option, but now I am trying to make the input box di ...

Position of JSON data response is inaccurate

Currently, I have a function that calls an API from the server in the following manner: getDataSet(callback) { request.open('POST', `${apiPath}`); request.setRequestHeader('Content-Type', 'application/x-ww ...

finding the index of a particular checkbox in a list

I am working with a list of checkboxes that are dynamically created using JavaScript, each contained within its own separate div element. I need to determine the position number of a specific checkbox within all checkboxes sharing the same class within a p ...

An issue with Rails 3 ajax call resulting in ActionView::MissingTemplate error

Currently, I am attempting to perform an ajax call without needing to return any data, or maybe just return a 200 status code. The error I encountered is: ActionView::MissingTemplate (Missing template .... Within the controller, this is my ajax method: ...

Uploading Forms with AJAX in MVC 3

Hello everyone, I am currently in the process of implementing an AJAX post for a form on my ASP.NET MVC project. I have a background in Rails, so this is quite new to me. However, I seem to be facing an issue where the form is not performing an AJAX post ...