Display a partial form in Rails using Ajax

There is a form displayed in the image below:

Next, I aim to render this partial from an ajax call, specifically from .js.erb. However, I am unsure how to pass an object to f from the partial. Take a look at the image below for reference:

Is there a way to successfully pass an object to f?

Answer №1

By adding the :remote => true attribute, you can make the button trigger an asynchronous (Ajax) call.

index.html.erb

<%= link_to "Add Journal", new_journal_path, remote: true, class: 'new_journal_button'%>

new.js.erb

$('.new_journal_button').after("<%= j render('form') %>");
$('.new_journal_button').hide();

If you wish to submit a form asynchronously using Ajax

_form.html.erb

<%= form_for(@journal, remote: true) do |f| %>
  <div class="field">
    <%= f.label "journal" %><br>
    <%= f.text_field :title, placeholder: 'Journal', autofocus: true, 'data-behavior' => 'submit_on_enter' %>
  </div>
<% end %>

Journals_controller.rb

  def index
     @journal = Journal.new
     @journals = Journal.all
  end

  def create
    @journal = Journal.new(journal_params)
    respond_to do |format|
      if @journal.save
        format.html { redirect_to @journal, notice: 'Journal was successfully created.' }
        format.js
      else
        format.html { render :new }
      end
    end
  end

Answer №2

After some contemplation, I figured out a way to update part of the form by replacing it in the controller rather than the view.

In this method, we create an instance of the form builder f within the controller and only render the partial into a string. We then escape and render the JavaScript into the Ajax reply as usual.

  def show
    respond_to do |format|
      format.js do
        helpers.form_for(@journal) do |f|
          out = render_to_string partial: 'journal_entry_transaction_fields', locals: {f: f}
          render js: %($('.journal-entry').html("#{helpers.j out}");)
        end
      end
    end
  end

A potential solution for the corresponding CoffeeScript section that is Turbolinks-friendly and utilizes jQuery for sending Ajax requests could be something like:

$(document).on 'change', '#something', (e) ->
  $.get
    url: "/path/to/your/controller/#{e.target.value}.js"

Answer №3

To streamline the process, consider passing the @journal object and utilizing fields_for @journal within a partial file.

In the .js.erb file:

$('.journal-entry').html("<%= j render partial: 'journal_entry_transaction_fields', object: @journal %>");

The Partial file in HTML.erb format:

<%= fields_for @journal do |f| %>
   ... your code here .....
<% end %>

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

What is the process for utilizing node modules within the Alexa Developer Console?

Struggling with creating an Alexa skill that utilizes a Node.JS API with a module requiring npm installation? Unable to upload the node modules due to the absence of an upload button and console for npm install? Seeking guidance on how to proceed? ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

Is there a way to customize the color of a React component from a different source?

I am currently utilizing a React component library called vertical-timeline-component-react. <Fragment> <Timeline> <Content> <ContentYear startMonth="12" monthType="t ...

Cutting-edge framework for Single Page Applications

Can you assist me in identifying the most recent framework suitable for creating single page applications? Your help is greatly appreciated. Thank you. ...

Calculate the total of an array with the help of the angular forEach function

function dialogController(generate, $scope) { $scope.profiles = generate.get_keys('::role'); $scope.content = {}; $scope.options = []; $scope.servers = {}; $scope.subs = {}; $scope.discountList = {}; $sco ...

Problem with using Twitter Bootstrap in IE11 when Browser Profile Enterprise is enabled

I am facing an issue with a Bootstrap 3 web page. Some machines have IE configured to load intranet pages in Enterprise profile mode, while others have the default Desktop profile set in IE11. This configuration has caused the layout to break completely. ...

Using Python and Selenium for login, encountering difficulty in locating the div element

# _*_coding:utf-8_*_ from selenium import webdriver driver=webdriver.Chrome() url="https://login.alibaba.com" driver.get(url) driver.implicitly_wait(3) print(driver.page_source) driver.quit() Attempting to use Selenium for logging in, but unable to locat ...

AngularJS HTTP POST request encountering issue with success function not functioning as expected

I am currently working on implementing a basic HTTP post request to insert data into my database. The following pages are involved: register.php contains the registration form. maincons.js houses the application controllers. sqlregister.php include ...

jQuery parallax effect enhances scrolling experience with background images

My website features a parallax design, with beautiful high-resolution images in the background that dominate the page. Upon loading the site, the landing page showcases a striking, large background image alongside a small navigation table ('about&apos ...

Is it feasible to commit an object on Vue X through Actions?

I have a question regarding Vue X and actions (with commit). Can an object be passed as input in Commit? Similar to: ... action{ ResetLoginStats({commit}){ commit({ 'SetMutation1':false, 'SetMutation2':true, &a ...

Increasing the padding at the top of the logo when scrolling down the page

When scrolling down the page, there seems to be extra padding above the logo that is throwing off the alignment with the rest of the site. I've been trying different solutions to correct this issue: //$('.navbar-brand').css({ 'padding- ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

Discovering the specific object ID that triggered an event in JavaScript

I am developing a webpage that includes JavaScript functionality. There is a specific function in the Javascript code which gets triggered by two different elements when clicked: 1. When a checkbox is clicked: $('#chkShowAll').click( functi ...

Combining multiple arrays of arrays in JavaScript

I am dealing with an array that contains nested arrays. This particular array is called template https://i.sstatic.net/QIs0Q.png template consists of 2 arrays, but the number can vary and there can be multiple levels of arrays within each one. Here' ...

Check if Ajax.BeginForm is validated against the model

I am just starting to learn ASP.Net MVC... One issue I'm facing is that I have a View that displays all the FilterTypes. However, I also need to include a search option in the same View using AJAX. I've managed to implement the AJAX functionalit ...

Steps for creating a basic JQuery function for dividing integers

My website constantly updates with real-time data from our PI server, refreshing every 10 seconds. I've been given the task to take two existing data points already on my page and calculate their division, then visualize the new result on a graph. Due ...

absence of data in ajax response (or HTTP status code 206 Partial Content)

Feeling frustrated because I've wasted two hours trying to solve a simple task that I've done numerous times before. I'm not even sure where to start looking now. Struggling to retrieve static content using ajax from local servers (Apache a ...

Vue - Seamlessly Editing and Creating Content Together

When using Laravel, I am attempting to pass data to a Vue component. Depending on whether the user enters the component through an edit URL or a create URL, we send either an array of data or null. Here is an example of how this process works: Blade view ...

Trouble arises when trying to link IE7 with jQuery

I am currently testing a website with jQuery. There is a plugin that, when hovered over, slides down to reveal another banner, subsequently sliding the banner below it down as well. I have added a link on the bottom banner using z-index, and although it wo ...