简体   繁体   中英

Ruby on rails — Jquery not submiting put request before another post request

I basically want to click a button and then submit a form when the user clicks another button. The form gets submitted but the button doesn't get clicked.

Method in the controller (put):

def set_everything
    user.update_column(:everything_set, true)
end

And then I have a form:

<%= form_tag("http://someotherwebsite.com/post_method", method: :post, id:"form")%>
     <%= some_field %>
     <button type="button" id="form-button">Done</button>
<% end %>

And then on the same view I also have another link_to:

<%= link_to set_everything_path, method: :put, id:"set-everything-button", style:"display:none" %>

My Jquery code:

$(document).ready(function(){
   $('#form-button').click(function(){
     $('#set-everything-button').trigger('click');
     setTimeout(function(){ $('form').submit();}, 2000);
   });
});

Now I have also tried using a button_to instead of link_to but it still doesn't get clicked and when I try it manually it works just fine.

Put the target url in a data attribute on the button:

<button type="button" id="form-button" data-trigger-url="<%= set_everything_path %>">Done</button>

Send the PUT request directly in your click handler:

$(document).ready(function(){
   $('#form-button').click(function(event){
     event.preventDefault();
     var form = $(this).closest('form');
     var url = $(this).data('trigger-url');
     $.ajax({
       url: url,
       method: 'PUT',
       dataType: 'html',
       success: function(){
         form.submit()
       }
     })
   });
});

Don't forget to send back 200 (OK) response from the controller action so that the javascript runs the success handler (and thus submits the form):

def set_everything
  user.update_columns(everything_set: true)
  head :ok, content_type: "text/html"
end

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