完全坚持使用Stripe进行AJAX表单提交

时间:2013-11-13 04:40:36

标签: javascript jquery ruby-on-rails ajax forms

我很沮丧。我正在使用Stripe为付款创建表单提交系统。基本上,表单对Stripe进行了AJAX调用,这给了我一个成功的标记,然后我用它来重新提交表单,也通过AJAX。如果表单成功,它会重定向到新页面,如果没有,它会在没有重新导航的情况下使用错误消息填充表单。这是我的表格:

<%= form_for([@issue, @issue_order]) do |f| %>
  <% if @issue_order.errors.any? %>
    <div class="error_messages">
      <h2><%= pluralize(@issue_order.errors.count, "error") %> occurred. </h2>
      <ul>
        <% @issue_order.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <% f.hidden_field :issue_id %>
  <%= f.hidden_field :stripe_card_token %>
  <div class="field">
    <%= f.label :email %>
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= label_tag :card_number, "Credit Card Number " %>
    <%= text_field_tag :card_number, nil, name: nil %>
  </div>
  <div class="field">
    <%= label_tag :card_code, "Security Code on Card (CVV) " %>
    <%= text_field_tag :card_code, nil, name: nil %>
  </div>
  <div class="field">
    <%= label_tag :card_month, "Card Expiration " %>
    <%= select_month nil, {add_month_numbers_true: true}, {name: nil, id: "card_month"} %>
    <%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year + 15}, {name: nil, id: "card_year"} %>
  </div>
  <div id="stripe_error"></div>
  <div class="actions"><%= f.submit "Purchase Issue", id: "submit_issue_order" %></div>
<% end %>
<div class="errors"></div>

以下是处理表单并设置条带信息的javascript:

var issueOrder;

$(function() {
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
  issueOrder.setupForm();
});

var issueOrder = {
  setupForm: function() {
    $('#new_issue_order').submit(function(e) {
      e.preventDefault();
      $('#submit_issue_order').attr('disabled', true);
      issueOrder.processCard();
      return false;
    });
  },
  processCard: function() {
    var card;
    card = {
      number: $('#card_number').val(),
      cvc: $('#card_code').val(),
      expMonth: $('#card_month').val(),
      expYear: $('#card_year').val()
    };
    Stripe.createToken(card, issueOrder.handleStripeResponse)
  },
  handleStripeResponse: function(status, response) {
    if (status == 200) {
      $('#issue_order_stripe_card_token').val(response.id);
      // $('#new_issue_order')[0].submit();
      $.ajax({
        type: "POST",
        url: $('#new_issue_order').attr('action'),
        data: { "issue_order": {
          "stripe_card_token": $('#issue_order_stripe_card_token').val(),
          "email": $('issue_order_email').val(),
          },
          "issue_id": $('#issue_order_issue_id').val()
        },
        dataType: "script"
      }, issueOrder.processOrder);
    }
    else {
      $('#stripe_error').text(response.error.message);
      $('input[type=submit]').attr('disabled', false)
    }
  }

这是我的控制器:

  def create
    charge = Stripe::Charge.create(
      :amount => 400,
      :currency => "usd",
      :card => params['issue_order']['stripe_card_token']
    )
    if charge['paid'] == true
      @issue_order = IssueOrder.new(email: params['issue_order']['email'], issue_id: params['issue_id'])
      if @issue_order.save
        @pdf_token = @issue_order.pdf_token
        PdfMailer.pdf_email(params['issue_order']['email'], @issue_order).deliver
      else·
        flash[:error] = []
        flash[:error].push("Your card was charged, but sadly we were unable to create·
        a record in the database. Please contact us for your copy of the issue.")
        respond_to do |format|
          format.js
        end
      end
    else
      # run checks for errors and return error messages
      flash[:error] = []
      flash[:error].push("There was an error in processing your payment.")
      render :json => {success: false}
    end
  end

典型的条纹设置。成功处理条带顺序时工作正常。好吧,它在我手动滚动AJAX调用之前做了,我假设如果我抛出一个respond_to |格式就行了。在重定向到成功页面的控制器中的成功案例中。但是,对于错误情况,我的控制器呈现create.js.erb,如下所示:

console.log('yo');
$('.errors').empty();
errors = xhr.getResponseHeader('X-Flash-Error').split(',');
<% flash[:error].each do |error| %>
  $('.errors').append($('<p>' + <%= error %> + '</p>'));
<% end %>
setTimeout(function() {
  $('.errors').empty();
}, 3500);

控制器清楚地到达文件并呈现它,如日志所示:

Started POST "/issues/1/issue_orders" for 127.0.0.1 at 2013-11-12 23:33:17 -0500
Processing by IssueOrdersController#create as JS
  Parameters: {"issue_order"=>{"stripe_card_token"=>"tok_102vmu2pSkyWUgPAToj334Oa"}, "issue_id"=>"1"}
   (0.4ms)  BEGIN
   (0.4ms)  ROLLBACK
  Rendered issue_orders/create.js.erb (0.1ms)
["Your card was charged, but sadly we were unable to create \n        a record in the database. Please contact us for your copy of the issue."]
Completed 200 OK in 1363ms (Views: 3.9ms | ActiveRecord: 0.8ms)

但是我的页面上没有发生任何事情,包括控制台日志!如果我不手动滚动AJAX并使用remote:true,它会变得更糟 - 它将我的submit()调用识别为HTML,并且不知道如何处理格式,导致出现未知格式错误。

帮助!

0 个答案:

没有答案