Performing an AJAX request to display a partial template in Rails 3

I have a dashboard for users where on the left side there is a sidebar with links such as Projects, Blogs, etc. I would like the user to be able to click on a link, let's say the "Projects" link, and then have the view for projects load up in the main area without refreshing the entire page. I have been trying to achieve this using AJAX, but unfortunately, things are not working as expected.

This is my understanding of how it should work. When the user clicks on the sidebar link in show.html.erb

<%= link_to 'Projects', '/dash', remote: true %>

where /dash is set in the config/routes.rb file to route to user's show action like this:

match '/dash' => 'users#show'

Then, the show action is triggered in users_controller.rb:

def show
    @user = User.find(params[:id])
    @projects = @user.projects

    respond_to do |format|
      format.html # renders show.html.erb
      format.js   # renders show.js.erb
    end
end

The show.js.erb file is executed. It includes this line:

$('#ajax').html("<%= escape_javascript(render(:partial => 'projects/index')).html_safe %>");

This line is intended to update the #ajax div in the show.html.erb:

<div id="ajax">
  <%= render :template => 'projects/index' %>
</div>

The app/views/projects/index.html.rb file loops through @projects and displays a list as follows:

<% @projects.each do |project| %>
  <p><%= project.name %></p>
<% end %>

However, despite following this process, it seems like I have missed something as it is not working. Can anyone point out where I might be going wrong? Is there a piece of code that needs to be adjusted elsewhere? I am using Rails 3.2.13, so the lines //=jquery and //=jquery_ujs in

app/assets/javascripts/application.js
should have imported the required jQuery and AJAX functionality.

Answer №1

The issue arises from your show.js.erb file where you attempt to render a partial that is not actually a partial. Remember, partial files should start with an underscore _.

To prevent code duplication, follow these steps:

# app/views/projects/show.js.erb
$('#ajax').html("<%= escape_javascript(render :partial => 'index', :locals => { :projects => @projects } ) %>");

# app/views/projects/index.html.erb
<%= render :partial => 'index', :locals => { :projects => @projects } %>

# app/views/projects/**_**index.html.erb
# Add the code from index.html.erb here
# Remember to replace @projects with projects
<% projects.each do |project| %>
  <p><%= project.name %></p>
<% end %>

Additionally, it is recommended to avoid using match in routes when you only need GET or POST methods. Opt for get instead of match.

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

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

The browser fails to render an EJS-generated page when responding to a Fetch request

Today, I encountered a strange issue that has left me puzzled. In summary, I have been sending a PUT request from a user form to the backend. Since forms do not natively support PUT/DELETE requests, I had to use a script to handle this task for me. let for ...

Struggling to access the height attribute from a CSS file

Hey there. I'm pretty confident that the solution to my query is quite simple. So, I have a .css file with this particular code snippet: div.site { text-align:center; border:2px solid #4b6c9e; padding:1px; margin-top:10px; font-size:medi ...

Using Swig's conditional extend tag with Express.js and Node.js to leverage dynamic content rendering

Is there a way to make the extend tag for the Swig templating engine conditional or able to use a passed variable? Instead of using this code: {% extends '../layouts/layout.view' %} I would prefer to do something like this: {% extends layout ...

Conceal particular table cells through jQuery

I am a beginner in the world of jQuery. My goal is to hide certain cells in a row when clicked, and have them displayed again when clicked once more. I've searched high and low for a solution, but all I find is how to hide entire rows. Here's an ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

What is the best way to include a substantial amount of HTML in a Vue.js template?

As a newcomer to Vue.js, I have a question regarding the rendering of a large amount of HTML in a Vue.js template. When I include around 500 lines of plain HTML code in my template and run npm run dev the compiling process becomes extremely slow or d ...

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Tips for sending information from PHP to Javascript using jQuery?

I am looking to move data from a PHP page that pulls information from MySQL, with the goal of displaying this data on my mobile app using Cordova. I plan to achieve this using JavaScript. Here is the PHP code I currently have implemented: if($count == ...

Choosing various choices using AngularJS

My goal seems simple using vanilla JS, but with AngularJS, I'm looking for the best way to achieve it within the framework. I aim to update the selected options in a multiple select box without adding or removing any options. Below is a snippet of my ...

What is the best way to showcase database content on the front-end within a div using ajax?

After clicking the button labeled "Get Reports" below the #search-results area, I want to display the content. The data will be filtered based on the selected date's content (refer to the screenshot). Current Issue: While I'm receiving the expec ...

Accessing the return value from an ASP.NET web service in JavaScript outside of the callback function

I am facing an issue with my ASP.NET web service that returns a simple string value. I have successfully called this web service using JavaScript and the script manager. However, I am in need of accessing the return value directly from where I made the cal ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

Pattern matching tool for identifying React components with an unlimited number of properties

Currently diving into MDX and experimenting with Regex to extract details on React components from Markdown files. The regex pattern I'm aiming for should: Detect all types of React components This includes identifying the opening tag <Component ...

Deliver real-time updates directly to clients using Django Channels and Websockets

Currently, I am working on a page that needs to display live-updating data to the client. The rest of the website is constructed using Django framework, so my approach involves utilizing Channels for this purpose. The data that needs to be showcased is st ...

When Ajax sends an HTTP Get request to an MVC Controller with a complex JSON object as a parameter, the controller receives it as null

I am currently working with three classes: public class MainSearch { public MainSearch() { SearchData searchData = new SearchData(); SearchMode searchMode = new SearchMode(); } public SearchData searchData { get; set; } ...

Issues with locating elements using jQuery within an AJAX request

I need assistance setting up AJAX pagination using jQuery. The code I'm trying to use is as follows: $('.pagination a').on('click', function(e) { e.preventDefault(); $.ajax({ type : 'GET', ...