单击按钮时,如何发送包含表单中包含的数据的电子邮件?

时间:2015-03-11 21:31:21

标签: php jquery html email

所以我只需要从我制作的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!";
}
?>

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

你有一些学习在你前面。幸运的是,有免费的材料可以帮助你。

我建议使用AJAX提交表单 - 这并不困难。完全没有。 AJAX的功能是允许您在不将用户导航到新页面的情况下提交表单。用户在提交表单时停留在页面上。这是一个免费的10分钟视频解释它:

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

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

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

  

FORMS摘要:表单由许多HTML字段(通常为<input>元素)组成,这些字段由<form></form>标记括起来。按下submit按钮后,表单数据将“POST”到表单标记的<form action="somefile.php"属性中指定的(通常为PHP)文件。基本上,表单元素收集在一系列varName = varValue对中,并发送到另一个(通常是PHP)文件进行处理。

     

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

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

提交表单后,接收(PHP)文件会收到表单数据:variable name ==> "name=" attributevariable contents ==> field contents

     

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

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


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

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1