提交Rails Jquery Modal表单,验证不起作用

时间:2013-02-24 06:43:24

标签: jquery ruby-on-rails ajax ruby-on-rails-3

3个并发问题:

  • 模态表单内联验证未显示
  • 模态表单未提交
  • 在哪里定义ajax之后发生的页面更改 提交? UJS文件,js根中的jquery等。

对于上下文,这是流程:

  1. 非用户点击“购买”按钮
  2. 'transactions / form'模式表单打开:包含一个表单,用于创建新事务和可选的新用户(注册)
  3. 表单包含条带信用卡字段和可选的密码/电子邮件字段,还包含有关帖子的信息的隐藏字段(ID,价格等...)
  4. 用户有两种选择: a。仅输入信用额度 b。输入信用额度和密码/电子邮件,即注册
  5. 点击提交
  6. IF:选项a,仅输入了信用详细信息
    • 验证卡
    • 收取信用卡
    • 关闭模式并对页面进行适当的更改
  7. IF:选项b,信用卡+注册详细信息已输入
    • 验证卡和用户详细信息
    • 创建用户
    • 创建客户并向客户收费
    • 关闭模式并对页面进行适当的更改
  8. 帖子已从“有效”更改为“无效”
  9. 我正在使用client_side_validations gem。

    按照上述步骤的粗略顺序,以下是我的购买按钮,模态表单,jquery和控制器的详细信息。

    查看:带有购买按钮和模态表单的帖子项目:

    /button that opens modal form
    %a.btn.buy-button{remote: :true,"data-toggle" => "modal", :href => "#buy_modal", :role => "button"} Buy
    
    /the modal form
    %div#buy_modal.modal{:role => "dialog",:style=>"display:none"}
      =render :partial => 'transactions/form'
    

    模态表格

      =form_for @transaction, :validate => true, :html => {:class => "form"} do |f|
        =yield(:user_validators)
        - if @user.errors.any?
          #error_explanation
          %h2= "#{pluralize(@user.errors.count, "error")} prohibited this group from being saved:"
          %ul
            - @user.errors.full_messages.each do |msg|
              %li= msg
    
        /POST DETAILS
        = f.hidden_field :stripe_card_token
        = f.hidden_field :price
        = f.hidden_field :tier_id
        = f.hidden_field :premium
        = f.hidden_field :notify_premium
        = f.hidden_field :user_id
        = f.hidden_field :customer_id
        /CREDIT CARD STUFF
        #credit-card{:style => @user.stripe_customer_id ? "display:none" : "display:block"}
          #credit-card-errors{:style => "display:none"}
            #stripe-error-message.alert-message.block-message.error
        %div.row-fluid
          = label_tag :credit_card_number
          = text_field_tag :credit_card_number, params[:credit_card_number], :class=>"credit-number span12"
        %div.row-fluid
          %div.span6
            = label_tag :expiry_date
            = date_select "", :expiry_date, {:discard_day => true, :order => [:month, :year], :use_month_numbers => true, :start_year => Date.today.year, :end_year => Date.today.year + 25}, {:class =>"credit-expiry inline"}
          %div.span3
          %div.span3.credit-cvv
            = label_tag :cvv, "CVV"
            = text_field_tag :cvv, params[:cvv], :class=>"credit-cvv input-block-level"
    
        /NEW USER STUFF
        =f.label :email
        =f.text_field :email
        =f.label :password
        =text_field_tag :password, params[:password]
    
        =f.submit "Save"
    

    管理模式的Jquery:

    $(document).ready(function() {
      var $buy_dialog = $('#buy_modal').dialog({ 
        autoOpen: false, 
        title: 'Edit',
        modal: true,
        draggable: false,
        buttons: {
                    "Save": function() {
                            $("#new_transaction").submit(function(){
                                var valuesToSubmit = $(this).serialize();
                                $.ajax({
                                    url: $(this).attr('action'), //sumbits it to the given url of the form
                                    data: valuesToSubmit,
                                    type: 'POST',
                                    dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
                                }).success(function(json){
                                    //act on result.
                                });
                                return false;
                            });
                            $('#buy_modal').dialog( "close" );
                    },
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                }
    
        });
    

    管理模态内联验证的Jquery

    $(document).ready(function(){
        $('.form').enableClientSideValidations();
        $('.form').on('shown', function() {
          $(ClientSideValidations.selectors.forms).validate();
        });
    };
    

    交易控制器,create操作:

      def create
        @transaction = Transaction.new(params[:transaction])
        @user = User.new(:email => params[:transaction][:email], :password => params[:password])
    
        respond_to do |format|
          if params[:password]
            #let's make a user and a transaction object
            if @transaction.save
              @user.save_with_payment
              format.html { redirect_to @transaction, notice: 'Transaction was successfully created.' }
              format.json { render json: @transaction, status: :created, location: @transaction }
            else
              format.html { render action: "new" }
              format.json { render json: @transaction.errors, status: :unprocessable_entity }
            end
          else
            if @transaction.save
              @transaction.payment(params[:transaction][:tier_id],params[:transaction][:price],params[:transaction][:premium],params[:transaction][:premium_notify])
              format.html { redirect_to @transaction, notice: 'Transaction was successfully created.' }
              format.json { render json: @transaction, status: :created, location: @transaction }
            else
              format.html { render action: "new" }
              format.json { render json: @transaction.errors, status: :unprocessable_entity }
            end
          end
        end
      end
    

    用户控制器,create操作:

    def create
        @user = User.new(params[:user])
        respond_to do |format|
    
          #OPTION A, explained above
          if params[:user][:password].nil?
            # Charge the card and don't make a user
            # get the credit card details submitted by the form
            token = params[:stripeToken]
    
            # create the charge on Stripe's servers - this will charge the user's card
            charge = Stripe::Charge.create(
              :amount => 1000, # amount in cents, again
              :currency => "usd",
              :card => token,
              :description => params[:email]
            )
    
          #OPTION B, explained above
          else
            # create user, customer, and charge them
            token = params[:stripeToken]
            if @user.save_with_payment(token)
              @user.payment()
              format.html { redirect_to @user, notice: 'User was successfully created.' }
              format.json { render json: @user, status: :created, location: @user }
            else
              #error message
              format.html { render action: "new" }
              format.json { render json: @user.errors, status: :unprocessable_entity }
            end
          end
        end
      end
    

    我意识到这是一个庞大的问题,但这是一个非常常见的项目元素。我已经通过堆栈溢出来搜索每个组件的答案,而且没有任何东西符合要求。

    Submit Form in Rails in a ajax way with jquery

    Jquery modal windows and edit object

    Jquery modal box form validations(试图重新发明轮子,而不是铁轨,指导不是规范的)

    Problems validating form input in a modal window with jquery(这里没有MVC,问题实际上没有回答)

    client_side_validations gem with formtastic in jquery modal view not working(未回答)

1 个答案:

答案 0 :(得分:2)

部分答案:

模态表单内联验证未显示

无法帮助你解决这个问题

模态表单未提交

  • rails已经烘焙了CSRF保护。由于您未传递所需的CSRF令牌,因此您的请求可能会被踢出
  • 您应该在表单选项中添加remote: true。它将让不显眼的rails驱动程序管理您的请求(不需要表单序列化),并根据响应触发自定义事件。有关详细信息,请参阅Rails 3 remote links and forms或仅查看Rails AJAX guides

在ajax提交后定义页面更改的位置? UJS文件,js根中的jquery等。

您可以使用js.erb文件进行响应,与html.erb文件相同,其中jQuery逻辑将在客户端上下文中执行。

我试图更详细地回答这个问题,但是你的逻辑是非常拜占庭的(我认为你在复制/粘贴期间丢失了选项A中的一些语句,因为此选项没有保存/格式)。作为旁注,这种情况将使数据 - 上下文 - 交互架构相关。