Send email with rails 4, mail form, and ajax?

别说谁变了你拦得住时间么 提交于 2019-12-09 07:33:36

问题


I am working on an app that has a contact form. It is a single page app, and I am using rails on the backend, and angular (not for the form) and bootstrap on the front end. I am trying to use ajax so I do not have to refresh the page. When I just have it submit with rails (using Mailform), it looks like it is working.

When I go into the console and type;

c = Contact.new(:name => "name", :email => "email@email.com", :message => "hi")

c.deliver

In the console, I get;

Rendered vendor/bundle/gems/mail_form-1.5.0/lib/mail_form/views/mail_form/contact.erb (2.9ms)

MailForm::Notifier#contact: processed outbound mail in 29.2ms

Sent mail to [EMAIL] (5.1ms)
Date: Fri, 25 Jul 2014 14:52:20 -0700
From: Name <email@email.com>
To: [EMAIL]
Message-ID: <53d2d194c8870_ec73fe2d54606d42885a@localhost.mail>
Subject: Onyx Contact Form
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<h4 style="text-decoration:underline">Onyx Contact Form</h4>


  <p><b>Name:</b>
  Name</p>

  <p><b>Email:</b>
  email@email.com</p>

  <p><b>Message:</b>
  Hi</p>


=> true

Which looks like it is working. However, I am not sure if it is, only because I am not getting anything to my email (but maybe email doesnt send locally?). When I try to submit with ajax and press "submit" nothing happens, so I know my javascript isn't right.

Here is the rest of my code;

index.html.erb

<div class="row">
    <%= bootstrap_form_for @contact ||= Contact.new do, remote: true |f| %>
    <div class="inner">
      <div class="col-md-7" id="form">
            <%= f.text_field :name, :required => true, :hide_label => true, :placeholder => "Name" %>
            <%= f.text_field :email, :required => true, :hide_label => true, :placeholder => "Email" %>
            <%= f.text_area :message, size: "60x10", :required => true, :hide_label => true, :plceholder => "Hello, we'd love to work with you" %>

            <%= f.submit 'Send Message', class: 'custom-button' %>
      </div>
    </div>
  </div>

contact.rb

class Contact < MailForm::Base
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname,  :captcha  => true

  # Declare the e-mail headers. It accepts anything the mail method
  # in ActionMailer accepts.
  def headers
    {
      :subject => "Onyx Contact Form",
      :to => "[MY_EMAIL]",
      :from => %("#{name}" <#{email}>)
    }
  end
end

contacts_controller.rb

class ContactsController < ApplicationController
  def new
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])
    @contact.request = request
    if @contact.deliver
      flash[:notice] = 'Thank you for your message. We will contact you soon!'
      redirect_to root_url
    else
      flash.now[:error] = 'Cannot send message.'
      render :new
    end
  end
end

main.js

$(function(){
    $("#form").submit(function(){
        var dataSet = $(this).serialize();
        $.ajax({
            type: "POST",
            url: $(this).attr("action"),
            data: dataSet,
            complete: function(){
                alert("Sent!");
            },
            error: function(){
                alert("Something went wrong!");
            }
        });
        return false;
    });
})

routes.rb

match '/contacts', to: 'contacts#new', via: 'post'
resources :contacts, as: 'home' #home so it doesn't go to another page

I also added some stuff in config files I found from other SO answers, and I'm not sure if it's doing anything or not. Normally I wouldn't use ajax to submit a form, but because it's single page, routing to another page isn't really an option. If this is too difficult using mail form, maybe Action Mailer is a better option? Any help pointing me in the right direction would be appreciated.


回答1:


First step, add this config.action_mailer.perform_deliveries = true to config/environments/development.rb

With that you can send emails in development mode.

Second step rails 4 use strong parameters, this means that you need to whilelist your parameters so in your controller add the following method:

def contacts_params
  params.require(:contact).permit(:name, :email, :message)
end

then change this line @contact = Contact.new(params[:contact]) with @contact = Contact.new(contacts_params)

Please do a try with these changes.

Edit:

In your routes you are calling to 'contacts#new' instead of 'contacts#create' so your code is not reached.

Also if you do not need remote: true since you are handling the submit stuff manually



来源:https://stackoverflow.com/questions/24965656/send-email-with-rails-4-mail-form-and-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!