douye1876
2017-02-19 17:51 阅读 103

必填属性和提交表单按钮

This is my code:

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" />

script in 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
" .
     "Reply-To: $mail
" .
     "X-Mailer: PHP/" . phpversion());

?>

With this code I can send mail if all fields are null too. I would add a control to send mail when all fields respect required attributes. Tnk you so much! Bye

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanbing6955 duanbing6955 2017-02-19 17:58

    This will happen because when submit button is clicked the ajax call is made to prevent such - make use of submit event regarding form in jquery, you can do as your wish with following code.

    First add id to the form like below:

    <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>
    

    Now for jquery code

     $(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!");
            }
    
        });
     })
    
    点赞 评论 复制链接分享

相关推荐