必填属性和提交表单按钮

时间:2017-02-19 17:51:17

标签: php ajax email attributes required

这是我的代码:

的index.php

<form action="">
<input placeholder="Name" class="form" id="nome" type="text" required/>
<input placeholder="Mail" class="form" id="mail" type="email" required />
<input placeholder="Object" class="form" id="oggetto" type="text" required />
<textarea placeholder="Message" id="text" class="form"></textarea>
<input class="formBtn" type="submit" id="submit"/>
<input class="formBtn" type="reset" />

index.php中的

脚本

    <script>
    $('#submit').click(function() {
        var nameform = $('#name').val();
        var mailform = $('#mail').val();
        var objectform = $('#object').val();
        var textform = $('#text').val();
        var mailcomplete = 'Name='+nameform+'&Mail='+mailform+'&Object='+objectform+
'&Message='+textform;

        $.ajax({
            type: "POST",
            url: 'php/mail.php',
            data: mailcomplete,
            success: function() {
            alert("Well Done!");
            }

        });
});

mail.php

    <?php

$name = $_POST['Name'];
$mail = $_POST['Mail'];
$object = $_POST['Object'];
$message = $_POST['Message'];

mail("mail@mail.it", $object, $message,
     "From: $mail\r\n" .
     "Reply-To: $mail\r\n" .
     "X-Mailer: PHP/" . phpversion());

?>

使用此代码,如果所有字段都为空,我也可以发送邮件。 当所有字段都遵循必需的属性时,我会添加一个控件来发送邮件。 非常感谢你!再见

1 个答案:

答案 0 :(得分:0)

这会发生,因为当点击提交按钮时,会调用ajax调用 - 在jquery中使用关于表单的提交事件,你可以按照你的意愿使用以下代码。

首先将ID添加到表单中,如下所示:

<form action="" id="formId">
   <input placeholder="Name" name="Name" class="form" id="name" type="text" required/>
   <input placeholder="Mail" name="Mail" class="form" id="mail" type="email" required />
   <input placeholder="Object" name="Object" class="form" id="oggetto" type="text" required />
   <textarea placeholder="Message" name="Message" id="text" class="form"></textarea>
   <input class="formBtn" name="submit" type="submit" id="submit"/>
   <input class="formBtn" name="reset" type="reset" />
 </form>

现在是jquery代码

 $(document).on('submit','#formId',function(e){
     // this will prevent form to submit
     e.preventDefault();
     // data need to send can be get with javascript serialize()
     var data = $("#formId").serialize();
     // now go for ajax call
     $.ajax({
        type: "POST",
        url: 'php/mail.php',
        data: data,
        success: function() {
        alert("Mail inviata correttamente!");
        }

    });
 })