[英]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:
<%= link_to set_everything_path, method: :put, id:"set-everything-button", style:"display:none" %>
My Jquery code: 我的Jquery代码:
$(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. 现在,我也尝试使用button_to而不是link_to,但是仍然无法单击它,当我手动尝试时,它可以正常工作。
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: 直接在点击处理程序中发送PUT请求:
$(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): 不要忘记从控制器动作中发回200(OK)响应,以便javascript运行
success
处理程序(并因此提交表单):
def set_everything
user.update_columns(everything_set: true)
head :ok, content_type: "text/html"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.