weixin_33704591 2012-11-29 14:49 采纳率: 0%
浏览 53

使用jQuery提交Rails表单

I am trying to submit a Rails form using jQuery and Ajax however it is not working and I am not sure why. I realize there is the remote: true to do things using AJAX but this is not enough in my case as I want to perform other jQuery actions when the submit buttons is clicked and give good feedback on the status of the action i.e success and failure. This is code I currently have the form:

<%= form_for @mail, id: "mail-form", url: subscription_mail_create_recipients_path(@mail) do |f| %>

    <strong>Choose the users you want to target..</strong><br/>

    <%= f.check_box :target_users %> Users                          

    <div class="actions">
    <a id="save-config" class="btn btn-primary purple-button">Save configuration</a>
    </div>
<% end %>

The jQuery:

    $('#save-config').click(function(){
        $('#mail-form').submit(function() {
            var valuesToSubmit = $(this).serialize();
            console.log(valueToSubmit);
                            $.ajax({
                                url: $(this).attr('action'), //sumbits it to the given url of the form
                                data: valuesToSubmit,
                                dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
                            }).success(function(json){
                                //act on result.
                            });
            alert("method failed");
                            return false; // prevents normal behaviour
        });
    });

I am trying to work off the example here Submit form in rails 3 in an ajax way (with jQuery)

I have no submit button, is that the reason it is not working? Any help would be appreciated thanks.

  • 写回答

1条回答 默认 最新

  • weixin_33676492 2012-11-29 15:46
    关注

    Your code does define function to be executed when the form is submitted. it does this for every click on your button. But what you want is to submit the contents of the form for every click. So try the following:

    $('#save-config').click(function(){
      var valuesToSubmit = $('#mail-form').serialize();
      console.log(valueToSubmit);
      $.ajax({
        url: $('#mail-form').attr('action'), //sumbits it to the given url of the form
        data: valuesToSubmit,
        dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
      }).success(function(json){
        //act on result.
      });
      return false; // prevents normal behaviour
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料