Search code examples
phpajaxemailattributesrequired

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


Solution

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