简体   繁体   中英

How to access the response for a form_tag in rails?

I have a form which submits number of info in Db.This form is on a modal popup. On click of submit tag, a new modal popup is displayed which has two buttons on click they show the data which the form has submitted. Now the problem is till when the controller call is finished, these buttons do nothing on click. So i want to add a spinner on the form popup on click of the submit button. and when the response comes true/ successful it shows the next popup.

my code 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 want to know how and where to access the json object or sys value returned from the controller.

I tried: Adding a class to the form and then

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

But could not succeed.Plese help and advise. Comment if i need to add some more code or explanation.

You are using form form_tag with remote true , which send the ajax request with js format not the json. If you render json response in js block instead of json in the controller like below, it should work.

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

Alternately you can render javascript file like this

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

in update.js.erb

Hope this helps.

extending maximus' code, you can use ajax to submit the form which can be more easy for you as per your case. You can try

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

and in your controller, render html of your modal you want to show with your submitted values which can be passed in instance variables. something like

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

this is a generic structure and you can change it to your relevant values. Hope it helps :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM