【问题标题】:How can I make, when clicking a button, send an email with the data included from the form?单击按钮时,如何发送包含表单中数据的电子邮件?
【发布时间】:2015-03-11 21:31:20
【问题描述】:

所以我只需要从我制作的 HTML 表单中收集信息并通过电子邮件发送。我怎样才能做到这一点?我需要 PHP 或类似的东西吗?我应该在 HTML 代码中添加什么?

$(function() {
/*
number of fieldsets
*/
var fieldsetCount = $('#formElem').children().length;

/*
current position of fieldset / navigation link
*/
var current     = 1;

/*
sum and save the widths of each one of the fieldsets
set the final sum as the total width of the steps element
*/
var stepsWidth  = 0;
var widths      = new Array();
$('#steps .step').each(function(i){
    var $step       = $(this);
    widths[i]       = stepsWidth;
    stepsWidth      += $step.width();
});
$('#steps').width(stepsWidth);

/*
to avoid problems in IE, focus the first input of the form
*/
$('#formElem').children(':first').find(':input:first').focus(); 

/*
show the navigation bar
*/
$('#navigation').show();

/*
when clicking on a navigation link 
the form slides to the corresponding fieldset
*/
$('#navigation a').bind('click',function(e){
    var $this   = $(this);
    var prev    = current;
    $this.closest('ul').find('li').removeClass('selected');
    $this.parent().addClass('selected');
    /*
    we store the position of the link
    in the current variable 
    */
    current = $this.parent().index() + 1;
    /*
    animate / slide to the next or to the corresponding
    fieldset. The order of the links in the navigation
    is the order of the fieldsets.
    Also, after sliding, we trigger the focus on the first 
    input element of the new fieldset
    If we clicked on the last link (confirmation), then we validate
    all the fieldsets, otherwise we validate the previous one
    before the form slided
    */
    $('#steps').stop().animate({
        marginLeft: '-' + widths[current-1] + 'px'
    },500,function(){
        if(current == fieldsetCount)
            validateSteps();
        else
            validateStep(prev);
        $('#formElem').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();    
    });
    e.preventDefault();
});

/*
clicking on the tab (on the last input of each fieldset), makes the form
slide to the next step
*/
$('#formElem > fieldset').each(function(){
    var $fieldset = $(this);
    $fieldset.children(':last').find(':input').keydown(function(e){
        if (e.which == 9){
            $('#navigation li:nth-child(' + (parseInt(current)+1) + ') a').click();
            /* force the blur for validation */
            $(this).blur();
            e.preventDefault();
        }
    });
});

/*
validates errors on all the fieldsets
records if the Form has errors in $('#formElem').data()
*/
function validateSteps(){
    var FormErrors = false;
    for(var i = 1; i < fieldsetCount; ++i){
        var error = validateStep(i);
        if(error == -1)
            FormErrors = true;
    }
    $('#formElem').data('errors',FormErrors);   
}

/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/
function validateSteps(){
    var FormErrors = false;
    for(var i = 1; i < fieldsetCount; ++i){
        var error = validateStep(i);
        if(error == -1)
            FormErrors = true;
    }
    $('#formElem').data('errors',FormErrors);
}

/*
validates one fieldset
and returns -1 if errors found, or 1 if not
*/

function validateStep(step){
    if(step == fieldsetCount) return;

    var error = 1;
    var hasError = false;
    $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input[required]:not(button)').each(function(){
        var $this       = $(this);
        var valueLength = jQuery.trim($this.val()).length;

        if(valueLength == '')
        {   

            hasError = true;
            $this.css('background-color','red');        
        }
        else
        {
            $this.css('background-color','yellow'); 
        }

    }


    );


    var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
    $link.parent().find('.error,.checked').remove();

    var valclass = 'checked';

    if(hasError)
    {

        error = -1;
        valclass = 'error';
    }
    $('<span class="'+valclass+'"></span>').insertAfter($link);

    return error;
}


/*
if there are errors don't allow the user to submit
*/
$('#registerButton').bind('click',function(){
    if($('#formElem').data('errors')){
        alert('Please correct the errors in the Form');
        return false;
    }   
});

我从一个网站获取了这个 .PHP 文件:

    <?php
if(isset($_POST['email'])) {

// Debes editar las próximas dos líneas de código de acuerdo con tus preferencias
$email_to = "my.email@email.com";
$email_subject = "Contacto desde el sitio web";

// Aquí se deberían validar los datos ingresados por el usuario
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {

echo "<b>Ocurrió un error y el formulario no ha sido enviado. </b><br />";
echo "Por favor, vuelva atrás y verifique la información ingresada<br />";
die();
}

$email_message = "Detalles del formulario de contacto:\n\n";
$email_message .= "Nombre: " . $_POST['first_name'] . "\n";
$email_message .= "Apellido: " . $_POST['last_name'] . "\n";
$email_message .= "E-mail: " . $_POST['email'] . "\n";
$email_message .= "Teléfono: " . $_POST['telephone'] . "\n";
$email_message .= "Comentarios: " . $_POST['comments'] . "\n\n";


// Ahora se envía el e-mail usando la función mail() de PHP
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

echo "¡El formulario se ha enviado con éxito!";
}
?>

如何实现它在单击“注册”按钮时发送电子邮件。我知道我需要在那里更改一些东西,但我该如何连接它们?

【问题讨论】:

  • 是的,JavaScript 不会自己发送电子邮件。在这种情况下,您必须使用表单提交或 ajax 将数据传递给 PHP。
  • 好吧,我也不知道。有什么建议吗?
  • 我想说只使用HTML默认提交并使用method="post",一旦你按下提交,你就可以从PHP端处理这一切。
  • 我添加了一个我找到的php文件。我该如何实现它?

标签: php jquery html email


【解决方案1】:

你还有一些学习要做。幸运的是,有一些免费材料可以帮助您。

我建议使用 AJAX 提交表单——这并不难。完全没有。 AJAX 所做的是允许您提交表单而无需将用户导航到新页面。提交表单时,用户停留在页面上。这是一个 10 分钟的免费视频来解释它:

https://phpacademy.org/videos/submitting-a-form-with-ajax

另外,下一个链接有大约 200 个 10 分钟的视频,你应该全部看完。但是发送表格的是第 98 - 103 课:

https://www.thenewboston.com/videos.php?cat=11

表单摘要:表单由许多 HTML 字段(通常是 &lt;input&gt; 元素)组成,这些字段由 &lt;form&gt;&lt;/form&gt; 标记包围。当按下submit 按钮时,表单数据被“发布”到表单标记的&lt;form action="somefile.php" 属性中指定的(通常是PHP) 文件。基本上,表单元素被收集在一系列 varName=varValue 对中,然后发送到另一个 (通常是 PHP) 文件进行处理。

每个 HTML 元素都可以有一个name= 属性:

<input type="text" name="fname" />

提交表单时,接收(PHP)文件接收表单数据为:variable name ==&gt; "name=" attributevariable contents ==&gt; field contents

简而言之,这就是 FORM 的工作原理。

您如何知道您的表单将使用哪种“接收”文件?如果您的网页托管在典型的“CPanel”托管帐户上,则可以使用 PHP。如果是 Microsoft 服务器,您将使用 M$ 解决方案(aspx?)


以下是一些非常简单的示例,可以帮助您了解 AJAX 的要点:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1

【讨论】:

    【解决方案2】:

    PHP 肯定不是从 Web 表单发送电子邮件的唯一方法,但它是一种非常常见的方法(尤其是对于创建第一个表单的人)。

    这是一个可以帮助您入门的参考资料,并解释了为什么其他方法(即仅 HTML、JavaScript)不能满足您的需求:

    http://www.html-form-guide.com/email-form/html-email-form.html

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 2015-06-08
      • 2012-03-10
      • 2015-01-19
      相关资源
      最近更新 更多