Sending back HTML in response to AJAX calls in Rails

After coming across David Heinemeier Hansson's interesting blog post regarding server-generated javascript, I was inspired to reassess my approach to handling AJAX calls within my Rails applications. According to David, the recommended method is to create a .js.erb template, which merges javascript with ruby code generated on the server, eliminating any need for DOM manipulation in client-side javascript.

Alternatively, one could opt to handle everything purely on the client-side by returning a JSON object representing the updated data from the server and utilizing javascript for all DOM manipulations.

I have reservations about the former approach for two main reasons:

1) Personally, I prefer using HAML and Coffeescript in my application, and incorporating vanilla javascript and ERB might introduce unnecessary complexity to my codebase by mixing languages (though I'm unsure if it's feasible to create .coffee.haml templates instead of js.erb).

2) The idea of cluttering my view folder with essentially javascript files containing snippets of embedded ruby does not sit well with me.

The latter approach, as outlined by David in his blog post, heavily relies on client-side javascript, potentially resulting in bloated javascript code and requiring client-side templates, possibly doubling the number of templates needed in extreme cases.

Therefore, after careful consideration, I have chosen to pursue a different strategy - setting the remote: true flag to enable links and forms to utilize AJAX for posting to the server.

In the controller, I handle everything as html and simply render without layout should the request be an AJAX request:

render partial: '<partial-name>', layout: false if request.xhr?
. This approach returns the HTML of the partial along with evaluated ruby code.

In an asset javascript file (such as <partial-name>.js.coffee), I listen for ajax:success events and append the received HTML content.

I find this method appealing because it allows me to maintain all my code in HAML/Coffeescript, omitting the need for javascript templates.

While I acknowledge that this solution may pose challenges as the application complexity increases, I still believe it raises a valid question: Is adopting this approach a poor choice for implementing AJAX functionality in a Rails application? Should I continue with this method or reconsider my approach? Are there disadvantages to returning HTML instead of JSON from an AJAX call? Your feedback is appreciated. :-)

Answer №1

Your method appears to be spot on. One small adjustment I would suggest is swapping out remote: true for a direct jQuery ajax call.

$(function(){
   $('#some_button').click(function() {
       $.ajax({
          // insert parameters here
      })
      .done(function(response){
           $('section').html(response);
      });
   });
});

Answer №2

When using remote: true, a JavaScript request is sent instead of an HTML request.

After the controller method is executed, it searches for a corresponding js.erb or js.haml file with the same name as the action that was just completed.

Within this file, you can write 'js' code to carry out any necessary actions after the controller has finished executing, such as updating a partial or refreshing the view.

If there is a function in a JavaScript asset file, that function can also be called from within this context.

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

Pulling Data in Vue.js using AJAX

Currently trying out Vue.js and I must say, it's impressively simpler than Angular. My single page app is utilizing vue-router and vue-resource to connect to my API backend. The primary app.js loads vue-router and vue-resource along with separate comp ...

Creating a dynamic user interface with multiple tab navigations using jQuery on a single web

On my current HTML page, I am facing an issue with multiple tab navigations. When I click on one navigation, it also affects the other tab navigations. I cannot seem to find a way to only affect the tab navigation that I am clicking on without hiding the ...

experiencing HTML glitches during AJAX calls

Recently, I came across an interesting script that simulates HTTP network delays for AJAX. You can check it out here: I'm wondering if there's a way to further enhance this approach to trigger a "server not found" error when making the AJAX call ...

Using a Handlebars function in JavaScript to appropriately format currency

In my handlebar template, I have the following code snippet: <span class="currencyFormatMe">{{_current_price}}</span> Here is an example of the output from the loop: Bid: $24000 I'm trying to format this output with commas and encounte ...

Two ways to make a call, whether it be from the same URL or from

I have implemented two methods, namely method1() and method2(). These methods are part of two separate web APIs which are published on different URLs. I am able to call these methods using the following URLs: www.aaa.com/api/firstcontroller/method1 www.b ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

Ways to adjust the child size within a dojo accordion

Currently, I am utilizing Dojo for a project where I have implemented pages with the use of dijit/layout/AccordionContainer. These accordion containers typically consist of three or more child containers whose heights dynamically adjust based on the availa ...

What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...

Accessing Facebook through the login page and being redirected

Is there a way to automatically direct users to a specific URL after logging in successfully with Facebook using the fb:login functionality? ...

BufferGeometry is not being displayed

After working extensively with BufferGeometry, I considered myself quite familiar with it. However, I am currently facing an issue while trying to create a simple square plane - there is no visible plane, no errors, and everything seems to be set up correc ...

What does the underscore before a function in JavaScript or PHP signify?

I am curious about the significance of the underscore symbol (_) when it is placed before a function or variable. Does it serve to simply describe something, or is it required for executing specific functions or calling certain methods? In JavaScript: va ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Toggle visibility of table columns by selected options (using jQuery)

I am seeking to create a dynamic table that only shows specific columns based on the selection in a dropdown menu. <table> <thead> <td colspan="5"> <SELECT name="menu"> <option value="eur">EUR</option> & ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

How do I extract a parameter when passing it to a promise in NodeJS?

Let me simplify this query. I need to fetch a parameter used in a promise. Here's the gist of the code: function foo(param) { return fromPromise(blabla, blabla2, param) .then((res) => { return res }).catch((error) => { console.log( ...

Correcting a hook being called outside of the function component's body

I created a custom ReactJS hook to manage specific mouse events, outlined below: const HealthcareServices = ({ filterToRemove, filters, onChange, onClear, selectedAmbulatoryCareFilterValue, shouldClear, }: Props): JSX.Element => { const cl ...

Steps for deploying a pre-built next.js application on Vercel without using Git integration.(Note: Make sure to follow these

I am in search of a straightforward method to deploy my next.js application from a private Gitlab repository and existing build pipeline to Vercel without uploading my source code or running builds on their platform; just deploying the already "built" next ...

Issues with expanding all nodes in the Angular Treeview function by Nick Perkins in London are causing difficulties

Currently utilizing the angular treeview project found here: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree After examining the functionality, it seems that this treeview is lacking search capabilities. To address this limitation, I deci ...

Enhancing the value within JSONjsonData

I am currently working on a quiz that categorizes individuals based on their personality types. The user's choices throughout the quiz will be assigned specific numerical values, which will be accumulated to determine the final result once the quiz is ...

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...