2016-09-05 7 views
0

私は連絡先情報を送信して連絡先オブジェクトを作成する機能を持つページを作成しています。連絡先を作成するためのコントローラは、次のとおりです。フォームが送信し、私はすべてのリダイレクト扱うが、私はJSで作成を処理したい場合は罰金オブジェクトを作成しますエラーを引き起こすAjax:フォーム送信時にPOST "/ [object%20Object]"を開始しました

def contact_params 
    params.require(:contact).permit(:name, :email, :phone, :company, :message) 
end 

:のcontact_paramsと

def create 
@contact = Contact.new(contact_params) 
if @contact.save 
    render json: @contact, status: :created 
else 
    render json: @contact.errors.full_messages, status: :unprocessable_entity 
end 
end 

。私は何の問題もなく、フォームの送信にする前に、このメソッドを使用しましたが、私は実行何らかの理由:

ActionController :: RoutingError(:

$(document).ready(function(){ 
    $('#new_contact').on('submit', function(ev){ 
    ev.preventDefault() 
    $.post({ 
     url: $(ev.target).attr('action'), 
     data: new FormData(ev.target), 
     processData: false, 
     contentType: false, 
     success: function(data){ 
     $('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm- offset-3"><h3>Thanks for contacting me,' + data.name + '. I will get back to you as soon as I can.</h3></div>') 
     document.getElementById('new_contact').reset() 
     $('#new_contact input[type="submit"]').prop('disabled', false) 
     }, 
     error: function(error){ 
     $('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm-offset-3"><h3>Sorry, I need at least a name and valid e-mail.</h3></div>') 
     $('#new_contact input[type="submit"]').prop('disabled', false) 
     } 
    }) 
    }) 
}) 

それはポストの要求とエラーで私のサーバーリターンをヒット[POST]/[object%20Object]と一致するルートはありません):

私はこれまでにこのエラーが発生したことはありませんでした。どんな助けもありがとうございます。

答えて

0

フォームにはRails 'remoteオプションを使用してください。これはAJAXでフォームを処理する組み込みメソッドです。

フォーム(あなたのビューで)次のようになります。そのまま

<%= form_for @contact, url: url_for(:controller => :contacts, :action => :create), remote: true, 'data-type': :json do |f| %> 
    <!-- insert the rest of your form here --> 
<% end %> 

お使いのコントローラが滞在することができます(それはちょうどそれがすでにやっている、フォームのAJAX要求にJSONを返す必要がある)、およびあなたのJSはこれに変更する必要があります:

$(document).ready(function() { 
    $("form#new_contact").on('ajax:success', function(event, data, status, xhr) { 
    // The returned JSON structure is available in data. 
    $('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm- offset-3"><h3>Thanks for contacting me,' + data.name + '. I will get back to you as soon as I can.</h3></div>'); 
    document.getElementById('new_contact').reset(); 
    $('#new_contact input[type="submit"]').attr('disabled', false); 
    }); 

    $("form#new_contact").on('ajax:error', function(event, xhr, status, error) { 
    console.log("AJAX request failed."); 
    // Do something about the failure so the user knows it happened. 
    }); 
}); 
+0

ありがとう、完璧に働いています。この問題のために見つけられる答えのほとんどは、私がやろうとしていたこととはまったく無関係でしたが、これはすぐに修正されました! – Rittersm

関連する問題