What is the process for retrieving the response from a form_tag in a Rails application?

I am facing an issue with a form that submits information to the database. The form is displayed on a modal popup, and upon clicking the submit button, a new popup appears with two buttons. However, these buttons remain inactive until the controller call is complete, causing a delay in showing the submitted data. To address this problem, I want to implement a spinner on the form popup when the submit button is clicked. Once the response from the controller is successful, the next popup should be displayed.

My current code snippet looks like this:

form:

= form_tag("/system/upload_form", method: 'post', enctype:   'multipart/form-data', remote: true) do
    ...
    ...
    =submit_tag("Submit",id: "submit_button", class: 'btn btn-default')  

controller:

sys = @system.update!(system_params)
respond_to do |format|
  format.js
  format.json { render :json => sys }

js:

$("#submit_button").click(function() {
    $('#modal_define_system').modal('hide'); // current popup
    $('#next-page').modal('show'); // next popup
});

Now I need help determining how and where to access the JSON object or value 'sys' returned from the controller.

I have attempted to add a class to the form and then bind an event, like so:

$('.form_class').bind('ajax:success', function() {
   console.log(sys);
});

However, I have not been able to achieve the desired result. Any advice or additional code suggestions would be greatly appreciated. Please leave a comment if further explanation or code examples are needed.

Answer №1

If you are using the form form_tag with remote true, it means that the ajax request is being sent in JavaScript format instead of JSON. To make it work, try rendering the JSON response within a JS block like the example below:

  respond_to do |format|
     format.js { render :json => sys } #this will work 
     format.json { render :json => sys } #this won't
   end

Alternatively, you can also render a JavaScript file like this:

$('#results_div').html("<%= @system.try(:title) %>")

within the update.js.erb file.

I hope this explanation helps solve your issue.

Answer №2

expanding on maximus' solution, you have the option to utilize ajax for form submission to streamline the process based on your requirements. Here's a suggestion:

$("#theForm").ajaxSubmit({url: '/system/upload_form', 
type: 'post'}).success(function(data){
$('#newModalContainer').html(data);
});

In your controller, consider rendering the HTML of the modal you wish to display with the submitted values, which can be passed through instance variables. For example:

def upload_form
#your code here
render :partial => 'new_modal_to_show'
end

This is a basic framework that can be customized according to your specific needs. I hope this information proves helpful :-)

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 best way to trigger a re-render of an app following a mutation?

I am currently working on a React application using Next.js. One of the features I am trying to implement is the ability for users to log in and trigger a re-render of the app to fetch the current logged-in user. Within my _app.js component, I have wrappe ...

The reduction method in d3 is producing a result of NaN

UPDATE: I have added a JSFIDDLE link and adjusted the original values in this post to match. However, the fiddle is not functioning properly due to the external CSV file. I attempted a solution found on this thread, but was unsuccessful. Nevertheless, you ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Utilizing AJAX with jQuery in Laravel 5

I am currently utilizing Laravel 5 for my project and I am implementing filters on some collections in my controller. The challenge I am facing is integrating AJAX as the intermediary between the blade template and Controller. Below is the jQuery code I am ...

Preventing text highlighting with javascript: A guide for developers

One potential solution involves using CSS, although it is considered a non-standard feature: ::selection { background: transparent; } ::-moz-selection { background: transparent; } Is there a method to achieve the same effect using JavaScript? Ad ...

Is there a way to make $animate.removeClass function within a directive without needing to use $eval

I have developed a custom directive that smoothly fades out and fades in the content whenever there is a change in the model. app.controller('myCtrl', function($scope, $interval) { $scope.number = 0; $interval(function() { $scope.number+ ...

Guide to removing a colon from my JSON.stringify output

I'm encountering an issue with a JSON.stringify function. It is adding a colon after the JSON object. axios.post('http://54.196.61.131/api/v0/user/250/product/add/scan', JSON.stringify({ name: currentProduct.product. ...

inputting a pair of parameters into a function

While creating an action for react-redux, I encountered a problem when trying to pass two variables into the function - dispatch and hosts. Strangely, the variable host is being logged as a function instead of its actual value. This is my code: export fu ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

To enhance your React Class Component, make sure to utilize the withStyles feature when

This particular component is not set as a default export component. I am attempting to apply some styles to it but struggling to figure out how to encapsulate it in an HOC. Hence, the current issue where it does not recognize the classes variable. import ...

Choosing Between Partial View with ng-route or ng-show/ng-hide: Which One is the Better Choice?

In my app, I have multiple tab views (four to five) where clicking on each tab will display content based on the tab selection. After trying two approaches - ng-route and ng-show/ng-hide, I found that ng-show/ng-hide is more efficient in terms of performa ...

Unable to receive response from Jquery ajax

Here is the HTML content I have created. <!DOCTYPE html> <html lang="en"> <head> <title>Test page</title> <script language="javascript" type="text/javascript" src="jquery-1.5.1.min.js"></script> ...

Getting Specific Information using Curl

Apologies if my English is not very good, I am in possession of a file, please verify this link So what exactly is google.php? <?php $link = 'https://drive.google.com/file/d/0B1xQLLJtrzJoaWUxUHdqY01mRGM/view'; $api = 'https://api.b ...

Decode a date and fetch it in the desired format within the ajax success function

Hey there, I've encountered an issue in retrieving the date value in ajax success. Can someone guide me on how to fix this problem? $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: {}, ...

AngularJS not compatible with Splice functionality

Currently, I am working on a form for an Items list that allows users to add, edit, and delete items. While the add and edit functionalities are working correctly, I am facing some issues with the delete functionality. Below is a snippet of my code that i ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

Issue with AngularJS: $compile function is not functioning as expected

In this particular code snippet, I am encountering an issue with the $compile function. What I am trying to accomplish is taking an item, adding it to the scope, and then compiling it to generate HTML. $http({ method: 'GET', ...

Concealed checkbox value in jQuery

I have a problem with setting the hidden checkbox "marketingPhone" to TRUE when the "marketingAAA" checkbox is checked as true. This part works fine. However, if any other checkbox on the page is set to TRUE, then it also sets "marketingPhone" to TRUE. I ...

How come I am getting an error message mentioning Selenium web driver when I am actually using the Watir webdriver?

I am in the early stages of learning Watir. I am attempting to create an automation script using Watir webdriver and cucumber. require 'rubygems' require 'watir-webdriver' require 'rspec-expectations' require 'cucumber&a ...

Creating interfaces for applications that are driven by events in JavaScript

When it comes to designing an application, traditional UML Class diagrams may not always be useful, especially for programs that do not heavily rely on classes. For instance, in a JavaScript application that is mainly event-driven, where you listen for eve ...