Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone!

I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page:

  1. Input their address Completing the form

  2. Submit the form Clicking to submit

  3. Update the view to display the address View updated

Should I utilize Stimulis or Ajax? I'm unsure which would be more advantageous! I attempted using plain JS but it ended up being repetitive and not very straightforward:

// file.js

document.querySelector(".form").addEventListener('submit', function () {
  address_form = document.querySelector(".address_form");
  address_form.style.display="none";
  document.location.reload();
  display_address = document.querySelector(".display_address");
  display_address.style.display = "block";
});
#file.html.erb

<div class="display_address">
  <% if current_user.line1? && current_user.postal_code? && current_user.city? %>
    <p>My current address: <%= current_user.line1 %>, <%= current_user.city %> <%= current_user.postal_code %></p>
  <% end %>
</div>
<div class="address_form">
  <%= simple_form_for(current_user, remote: true, html: { id: "add“dd”} ) do |f| %>
  <%= f.input :line1, label: 'My address' %>
  <%= f.input :city, label: 'City' %>
  <%= f.input :postal_code, label: 'Postal Code' %>
  <%= f.submit %>
  <% end %>
</div>

In summary, I aim for the user to input their address in the form, submit it, update my database, and refresh the view with the newly submitted address.

Thank you for your assistance!

Answer №1

To handle the response, you can utilize the controller's javascript functionality. Here is an example: file.html.erb

<%= simple_form_for(current_user, remote: true, format: :js, html: { id: "addddd"}) do |f| %>

users_controller.rb

def create
  # implement your own business logic here
  render 'create'
end

users/create.js.erb

document.getElementById("formId").innerText = "Insert other HTML text or use render() method."

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

The body tag mysteriously disappears after the function is called within the $().html() command

As I delve into scraping the source code of a website, I encounter an interesting phenomenon. Initially, when I print out the complete source code, everything appears as expected. However, upon attempting to print an actual DOM, I notice a slight change i ...

When initiating the Grunt Express Server, it prompts an issue: Error: ENOENT - the file or directory 'static/test.json' cannot be found

I'm currently in the process of updating my app to utilize the Express Node.js library. As part of this update, I have made changes to my Grunt.js tasks to incorporate the grunt-express-server package. However, after running the server successfully, I ...

:host background color may be missing, but the font size has been boosted?

Check out this demo where the CSS is applied to the :host element or <hello>. The font size increases but the background color remains unchanged. What do you think? styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) ...

Retrieving an item from AsyncStorage produces a Promise

Insight I am attempting to utilize AsyncStorage to store a Token after a successful login. The token is obtained from the backend as a response once the user clicks on the Login button. Upon navigating to the ProfileScreen, I encounter difficulties in ret ...

Avoid modifying the HTML DOM structure after utilizing the JQuery Load() method

Within an HTML Page, the Ajax Load() function is utilized to load additional HTML files into the current HTML document by targeting a specific element. When clicking on Links, the other HTML pages load correctly. However, despite the code being loaded usin ...

Methods for applying a style property to a div element with JavaScriptExecutor in Selenium utilizing C#

I have been attempting to change the style of a div element using JavascriptExecutor in C#, but so far, nothing has happened. IJavaScriptExecutor js = (IJavaScriptExecutor)driver; IWebElement element = driver.FindElement(By.XPath("//div[contains(@class, ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

Content Security Policy in Firefox Extension blocking local DataTables js

After downloading the js for DataTables, I attempted to load it onto my Firefox extension but encountered a Content Security Policy block: Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src moz-ext ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

When setValue is called on VCheckbox in Vuetify, it emits an event called "update:modelValue"

After setting a value for the checkbox, I encountered a warning message: [Vue warn]: Component emitted event "update:modelValue" but it is neither declared in the emits option nor as an "onUpdate:modelValue" prop. Example.vue <script setup lang="t ...

Helping individuals identify the HTML5 Geolocation notification

Currently working on a website that requires users to accept the browser prompt for location sharing. Many users seem to overlook this prompt, which can lead to issues. The main problem we are facing is that each browser displays this prompt differently: ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

What is the best way to dynamically render classes based on conditions in a table using React Bootstrap?

I am looking for a way to dynamically change the color of a class based on the transaction data in a table. import React from "react"; import Table from "react-bootstrap/Table"; import "./TableComponent.css"; const TableComponent = ({ Movement }) =&g ...

Tips for incorporating input form values into Google Charts

I'm facing an issue with my code where I have created a form to display submitted values in the google chart. When trying to load drawChart() after clicking the submit button, the drawChart() function is getting called onload instead. Can someone help ...

Creating a typewriter effect with Vue Js

Hey there, I'm having some trouble with the code below while working on my Vue project. It seems to be functioning correctly, but for some reason it's not working in my Vue environment. const text = document.getElementById("text"); const phrase ...

v-for loop to populate dropdown menu with identical values

Recently, I started working on a points counter app using Vue.js and encountered some issues with the v-for loop and dropdown menu functionality. Within my Vue.js application, I have an array of players as shown below: var app = new Vue({ el: '#l ...

Substitute the functions within a Node.js module with simulated functions

I am currently working on a Node.js project that serves as an API wrapper. To ensure the reliability of my code, I am writing unit tests using nodeunit and need to incorporate mock functions into the module. For instance, I require a function that mimics s ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...