简体   繁体   中英

Required attribute and submit form button

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\r\n" .
     "Reply-To: $mail\r\n" .
     "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

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!");
        }

    });
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM