【问题标题】:Submission of Rails Jquery Modal form with validations not working提交带有验证的 Rails Jquery 模态表单不起作用
【发布时间】:2013-02-09 13:21:48
【问题描述】:

3 个并发问题:

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

对于上下文,这是流程:

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

我正在使用 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(未回答)

【问题讨论】:

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


    【解决方案1】:

    部分答案:

    模态表单内联验证未显示

    在这方面帮不了你

    模态表单未提交

    • rails 具有内置的 CSRF 保护。您的请求可能会因为您没有传递所需的 CSRF 令牌而被踢出
    • 您应该将remote: true 添加到您的表单选项中。它将让不显眼的 Rails 驱动程序为您管理请求(无需表单序列化),并根据响应触发自定义事件。请参阅Rails 3 remote links and forms 或直接Rails AJAX guides 了解更多信息

    在哪里定义 ajax 提交后发生的页面更改? UJS文件,js根目录下的jquery等。

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

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

    【讨论】:

    • 哎呀...我误按了保存。待续
    • 不用担心。我的逻辑肯定是错综复杂的。让我发布一些编辑以澄清
    • 添加了事务控制器——实际上是由模态调用的
    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多