如何捕获表单值并通过电子邮件发送它们作为ajax请求?轨道 [英] How to capture form values and send them via email as ajax request ? Rails

查看:320
本文介绍了如何捕获表单值并通过电子邮件发送它们作为ajax请求?轨道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图设置一个简单的表单,用户在其电子邮件地址中输入订阅时事通讯。然后,我收到一封电子邮件,其中包含用户的电子邮件地址。



这是我到目前为止所尝试的内容:



 <%= form_for:subscribe,id:'sub_form'do | f | %GT; 
< input type =emailname =emailplaceholder =您的电子邮件地址id =sub_email>
< button class =btn btn-successtype =submitid =sub_btn>订阅< / button>< br>

<%end%>

路线

  post'subscribe /:email',:to => 'welcome3#subscribe',如:email_subscribetion

控制器:

  class Welcome3Controller< ApplicationController 
def subscribe
EmailMeMailer.confirmation()。deliver
end
end

邮件:

  class EmailMeMailer< ApplicationMailer 
默认来自:info@example.com

def确认
@greeting =Hi

邮件至:my_email_address @ gmail .com,主题:订阅确认
结束
结束

jQuery Ajax方法:

  $('#sub_form')。submit(function(e){
e.preventDefault();
})。validate({
rules:{

email:{
required:true,
email :true
},

},
submitHandler:function(form){

var btn = $('#sub_btn');
btn.button('loading');
setTimeout(function(){
btn.button('reset');
},3000);

$ .ajax({
type:'POST',
url:'/ subscribe',
// data:form.serialize(),
dataType:'json' ,
async:true,
data:{
csrfmiddlewa retoken:'{{csrf_token}}',
sub_email:$('#sub_email')。val(),
},

成功:function(json){

$('#sub_output')。html(json.message);
$(#sub_email)。prop('disabled',true);
}
});

返回false; //演示
}
});

我被困在:如何捕获提交的电子邮件地址并将其发送给自己?我没有使用任何模型来保存数据。此外,根据

解决方案

您可以在控制器中获取发布数据,并将其作为一个参考邮件行动。



编辑:上面的解决方案在这里工作。

HTML:



 <%= form_for:subscribe,html :{id:'sub_form'} do | f | %GT; 
< input type =emailname =emailplaceholder =您的电子邮件地址id =sub_email>
< button class =btn btn-successtype =submitid =sub_btn>订阅< / button>< br>

<%end%>



Javascript:



 <脚本> 
$('#sub_form')。submit(function(e){
e.preventDefault();
})。validate({
rules:{
电子邮件:{
required:true,
email:true
},
},
submitHandler:function(form){
$ .ajax({
type:'POST',
url:'/ subscribe',
dataType:'json',
async:true,
data:{
csrfmiddlewaretoken:'{{csrf_token}}',
sub_email:$('#sub_email')。val(),
},
成功:函数(json){
$ ('#sub_output')。html(json.message);
$(#sub_email)。prop('disabled',true);
}
});

返回false;
}
});
< / script>



控制器(app / controllers / welcome3_controller.rb)



  class Welcome3Controller< ApplicationController 
def subscribe
EmailMeMailer.confirmation(params [:sub_email])。deliver_now

respond_to do | format |
format.json {head:ok}
end
end
end

PS: .deliver 方法是已弃用。您应该使用 .deliver_now 来代替它。



邮件程序:(app / mailers / email_me_mailer.rb) h3>

  class EmailMeMailer< ApplicationMailer 
默认来自:info@example.com

def确认(电子邮件)
@greeting =嗨
@email =电子邮件

邮件至:my_email_address@gmail.com,主题:订阅确认
结束
结束



Mailer View:(app / mailers / email_me_mailer.rb)



 电子邮件:< %= @email%> 



路线:(config / routes.rb)



 发布'/ subscribe'=> 'welcome3#subscribe'

PS:

1)不要忘记在
app / views / layouts / mailer.text.erb 中生成邮件布局。


$ 2)请记住,布局和视图的扩展取决于您在邮件程序中定义的内容类型。如果是文本(默认),扩展名为 .text.erb 的文件,如果是HTML,则文件将具有 .html.erb


I'm trying to setup a simple form where the user types in his email address to subscribe for a newsletter. I then receive an email with the user's email address.

This is what I tried so far:

The form:

<%= form_for :subscribe, id: 'sub_form' do |f| %>
    <input type="email" name="email" placeholder="Your email address" id="sub_email">
    <button class="btn btn-success" type="submit" id="sub_btn">Subscribe</button><br>
    <p id="sub_output" class="lead" style="color: white;"></p>
<% end %>

The route

  post 'subscribe/:email', :to => 'welcome3#subscribe', as: "email_subscribtion"

The controller:

class Welcome3Controller < ApplicationController
  def subscribe
    EmailMeMailer.confirmation().deliver
  end
end

The mailer:

class EmailMeMailer < ApplicationMailer
    default from: "info@example.com"

  def confirmation
    @greeting = "Hi"

    mail to: "my_email_address@gmail.com", subject: "subscribtion confirmation"
  end
end

JQuery Ajax method:

$('#sub_form').submit(function(e) {
    e.preventDefault();
  }).validate({ 
    rules: {

      email: {
        required: true,
        email: true
      },

    },
    submitHandler: function (form) {

      var btn = $('#sub_btn');
      btn.button('loading');
      setTimeout(function() {
        btn.button('reset');
      }, 3000);

      $.ajax({
        type: 'POST',
        url: '/subscribe',
        // data: form.serialize(),
        dataType: 'json',
        async: true,
        data: {
          csrfmiddlewaretoken: '{{csrf_token}}',
          sub_email: $('#sub_email').val(),
        },

        success: function (json) {

          $('#sub_output').html(json.message);
          $("#sub_email").prop('disabled', true);
        }
      });

         return false; // for demo
     } 
 });

I'm stuck at: how do I capture the submitted email address and send it to myself ? I'm not using any models to save data. Also, according to this tutorial, Mailer does not have access to the POST request.

Bear in mind that I'm converting a Django app to RoR so that I can deploy it on cPanel. You can see the Django app here: the form is in the footer.

This is the view:

<h1>Welcome3#subscribe</h1>
<p>Find me in app/views/welcome3/subscribe.html.erb</p>

EDIT:

Also, in my Django app I send to this url:

url: '/subscribe/'

data: {
    csrfmiddlewaretoken: '{{csrf_token}}',
    email: $('#sub_email').val(),
    },

How should this be different in Rails ?

This is the JQuery Ajax request together

submitHandler: function (form) {

    var btn = $('#sub_btn');
    btn.button('loading');
    setTimeout(function() {
      btn.button('reset');
    }, 3000);

    $.ajax({
      type: 'POST',
      url: '/subscribe/',
      // data: form.serialize(),
      dataType: 'json',
      async: true,
      data: {
        csrfmiddlewaretoken: '{{csrf_token}}',
        email: $('#sub_email').val(),
      },

      success: function (json) {

        $('#sub_output').html("Thanks");
        $("#sub_email").prop('disabled', true);
      }
    });

       return false;
    } 

EDIT 2:

At this stage when I click on the subscribe button, I receive this routing error:

Routing Error No route matches [POST] "/"

Rails.root: C:/Sites/payligent

Application Trace | Framework Trace | Full Trace Routes

Routes match in priority from top to bottom

Helper HTTP Verb Path Controller#Action Path / Url Path Match root_path GET / welcome#index

package_signup_path GET /pricing/:level(.:format) welcome2#pricing

email_subscribtion_path GET /subscribe/:email(.:format) welcome3#subscribe

解决方案

You can get post data inside the controller, and pass it as an argument to the mailer action.

EDIT: The solution above worked here.

HTML:

<%= form_for :subscribe, html: { id: 'sub_form' } do |f| %>
  <input type="email" name="email" placeholder="Your email address" id="sub_email">
  <button class="btn btn-success" type="submit" id="sub_btn">Subscribe</button><br>
  <p id="sub_output" class="lead" style="color: white;"></p>
<% end %>

Javascript:

<script>
$('#sub_form').submit(function(e) {
  e.preventDefault();
}).validate({
  rules: {
    email: {
      required: true,
      email: true
    },
  },
  submitHandler: function (form) {
    $.ajax({
      type: 'POST',
      url: '/subscribe',
      dataType: 'json',
      async: true,
      data: {
        csrfmiddlewaretoken: '{{csrf_token}}',
        sub_email: $('#sub_email').val(),
      },
      success: function (json) {
        $('#sub_output').html(json.message);
        $("#sub_email").prop('disabled', true);
      }
    });

    return false;
  }
});
</script>

Controller (app/controllers/welcome3_controller.rb)

class Welcome3Controller < ApplicationController
  def subscribe
    EmailMeMailer.confirmation(params[:sub_email]).deliver_now

    respond_to do |format|
      format.json { head :ok }
    end
  end
end

PS: The .deliver method was deprecated after v2.3.8. You should use .deliver_now instead of it.

Mailer: (app/mailers/email_me_mailer.rb)

class EmailMeMailer < ApplicationMailer
    default from: "info@example.com"

  def confirmation(email)
    @greeting = "Hi"
    @email = email

    mail to: "my_email_address@gmail.com", subject: "subscribtion confirmation"
  end
end

Mailer View: (app/mailers/email_me_mailer.rb)

Email: <%= @email %>

Routes: (config/routes.rb)

post '/subscribe' => 'welcome3#subscribe'

PS:

1) Don't forget to generate mailer layout on app/views/layouts/mailer.text.erb.

2) Remember that the extension of layout and view depends on what type of content-type you defined in the mailer. If is text (default), the file you have extension .text.erb, and if is HTML the file will have .html.erb.

这篇关于如何捕获表单值并通过电子邮件发送它们作为ajax请求?轨道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆