Content not being displayed in Rails 4 with AJAX using Bootstrap 3 Modal

Despite researching several resources on BS modals with AJAX, such as the one found here: Bootstrap Modal in Rails Keeps displaying the first record, I am still encountering issues.

Upon implementing AJAX (using JQuery 2.1.1), the modal successfully opens, but the modal-body remains empty.

My objectives are twofold: A) to directly showcase an attribute (as demonstrated in the code below) for illustrative purposes, and B) subsequently display the show and edit views through partials.

Below is the relevant code:

/controllers/security_questions_controller.rb

def index
  @security_questions = SecurityQuestion.all
  respond_to do |format|
    format.html
    format.json
  end
end

def show 
  @security_question = SecurityQuestion.find(params[:id])
  respond_to do |format|
    format.html
    format.json
  end
end  

/views/security_questions/index.html.erb

<% @security_questions.each do |security_question| %>
. . .
  <td><%= link_to 'Show', security_question_path(security_question), data: {toggle: "modal", target: "#myModal"}, remote: true %></td>
. . .
<% end %>

. . .

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
. . .
      <div class="modal-body">   
      </div>
. . .
</div>

/views/security_questions/show.js.erb

$("#modal-body").html('<%= j(render @security_question.id) %>');
$('#myModal').modal('show');

The firebug console indicates a successful call when attempting to open the modal

GET http://localhost/security_questions/3   200 OK 1.21s
. . .
<div class="row-fluid">
  <div class="col-sm-offset-4 col-sm-4">
  What is the name of your first pet?
  </div>
</div>

No errors appear in log/development.log

Started GET "/security_questions/3" for 127.0.0.1 at 2014-12-27 10:44:13 -0800
Processing by SecurityQuestionsController#show as JS
  Parameters: {"id"=>"3"}
  SecurityQuestion Load (0.2ms)  SELECT  `security_questions`.* FROM `security_questions` WHERE `security_questions`.`id` = 3 LIMIT 1
  Rendered security_questions/show.html.erb within layouts/application (2.8ms)
  Rendered layouts/_shim.html.erb (0.6ms)
  Rendered layouts/_header.html.erb (15.4ms)
  Rendered layouts/_flash.html.erb (1.0ms)
  Rendered layouts/_footer.html.erb (2.3ms)
Completed 200 OK in 1164ms (Views: 1136.1ms | ActiveRecord: 1.9ms)

Answer №1

If you are trying to update the modal-body content, make sure you are targeting it correctly. Instead of using a class selector, use an ID selector like this:

$("#modal-body").html('<%= j(render @security_question.id) %>');

If your modal-body is actually a class, then change your code to:

$(".modal-body").html('<%= j(render @security_question.id) %>');

Alternatively, you can modify your HTML from:

<div class="modal-body"></div>

To:

<div id="modal-body"></div>

Answer №2

It seems like the issue arises from attempting to showcase the modal using both data attributes and the programmatic API simultaneously, which may not be compatible. Given that the modal's content is dynamically generated through an AJAX request, I would suggest the following modification:

BEFORE

  <td><%= link_to 'Show', security_question_path(security_question), data: {toggle: "modal", target: "#myModal"}, remote: true %></td>

AFTER

  <td><%= link_to 'Show', security_question_path(security_question), remote: true %></td>

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

Unable to select jQuery dialog based on class name for elements loaded via Ajax

Update: issue resolved: By using event delegation, all 'problematic' elements that were dynamically created after the page loaded are now properly bound to the jQuery event. Original inquiry: I encountered this particular piece of code in my P ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

What methods can I use to prevent jquery.address from modifying the URL in specific scenarios?

I am utilizing a plugin called jquery.address to manage browser history states on my ajax-heavy website. However, there is a specific scenario where I need to prevent the $.address.change() function from being triggered by a certain link. For instance, in ...

Troubleshooting issue: jQuery/Ajax selector not functioning as expected

After using jQuery.ajax() to fetch HTML content from a PHP source and inject it into an element on the page, I've noticed that jQuery selectors do not work on the elements within that loaded HTML. Is this a common issue or should I provide an example ...

jQuery AJAX event handlers failing to trigger

It's driving me crazy! I've been using jquery's ajax for years, and I can't seem to figure out why the success, error, and complete events won't fire. The syntax is correct, the service it's calling works fine, but nothing hap ...

Comparison between JSON Serializers and .NET Serialized Classes for Retrieving jQuery AJAX Result Data

What is the best method for transferring data from a .NET (C#, VB.NET) Web Service to the client-side using JQuery AJAX? A) Utilizing Newtonsoft JSON serialization, for example: <WebInvoke(Method:="*", ResponseFormat:=WebMessageFormat.Json, UriTemplat ...

Techniques for transmitting stringified JSON data from the view to the controller in MVC4

I am struggling to properly send a stringified JSON object when a button is clicked. Despite being able to call the necessary Action method upon button click, the parameter is passed as null. MemberLogin.cshtml <input type="button" value="» Continue" ...

Leveraging Deferred in conjunction with AJAX

I am facing an issue with a series of JavaScript functions that make database calls using AJAX. I need these functions to finish executing and update variables before moving on to the final function. I have attempted to use jQuery $.when but it is not work ...

When implementing Ajax with a Spring controller, it will redirect the user to a different location

I am currently working on developing a Spring MVC application similar to a "Cinema" app. I have implemented a RestController with a Get method that produces JSON responses. private SessionService sessionService; public SessionController(SessionService ses ...

Instantly change the default value with Ajax selection

My current setup involves using Ajax to populate a select HTML element with values from an array returned by PHP. Here is the Ajax code snippet: <script type = "text/javascript"> $(document).ready(function(){ $('#fds_categories&ap ...

What is the best way to send a List in the model as a parameter for an AJAX request?

I'm currently using MVC 4 ASP.net with Razor views and I have an issue with refining my search results using AJAX calls. The current approach involves creating methods in the controller that include all the search filters, which has resulted in a meth ...

Issues with Chrome causing Ajax synchronous requests to fail

Is the latest release of Chrome no longer supporting Synchronous Ajax calls? We're encountering an error with our Synchronous Ajax requests after updating to version 73.0.3683.103. Interestingly, Synchronous calls are still functioning properly on Fir ...

Is Jquery getting imported correctly, but AJAX is failing to work?

I am currently working on a Chrome extension that automatically logs in to the wifi network. I have implemented AJAX for the post request, but when I inspect the network activity of the popup, I do not see any POST requests being sent. Instead, it only sho ...

Leverage AJAX data to dynamically generate an input field within a Laravel application

. Hey everyone, I'm currently working on implementing ajax for a search functionality. The goal is to display links to the search results' pages along with checkboxes next to each result, allowing users to select orders for printing. Although I ...

Using jQuery to send legitimate JSON data in the request payload

After checking the jQuery Ajax documentation, it seems that by default, data gets serialized as a query string when sending requests. However, I learned that setting processData:false should allow me to send actual JSON in the request body. The problem is, ...

How can I send a JavaScript array to a Controller action using jQuery in Java?

I have a JavaScript array in my Razor view and I am calling a GET action of the controller from my MVC view using $.ajax. What parameter type should be used for the Controller action to accept the JavaScript array passed from the view? I attempted to us ...

`json: Alert not displaying response data`

Currently, I am utilizing the following Ajax code to retrieve data from the server. $.get("http://***/umbraco/Api/SomeApi/SignIn",{apiVersion : 1,email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee0efe3ebcee9e3efe7e2a0ed ...

A vibrant loading animation within a pop-up window

I have implemented an ajax spinner on my page using the following code: $(document) .ajaxStart(function () { $loading.show(); }) .ajaxStop(function () { $loading.hide(); }); Now, I want to display the spinner ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

Android Browser is experiencing issues with returning JSON data consistently after making an AJAX call

When I make an ajax call to an API for JSON data, everything works perfectly with other browsers. However, when using the Android Browser, the response seems to act strangely. I have added a console log using weinre to catch the returned data. Can anyone h ...