Send selected items via email form

Asked

Viewed 58 times

0

I have a contact form that uses JS to validate and PHP to send, works very well with inputs text and the like, I would like to implement select in it. I’ll pass my codes here:

HTML form:

<form name="sentMessage" id="contactForm" style="width: 842px" novalidate>
                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Nome*</label>
                        <input type="text" class="form-control" id="name" required data-validation-required-message="Por favor, insira seu nome.">
                        <p class="help-block"></p>
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Tipo de Inscrição</label>

                        <select class="form-control" name="tipo">
                          <option value="integral">Integral</option>
                          <option value="estudante">Estudante</option>
                          <option value="cref">CREF</option>
                          <option value="estagio">Estágio</option>
                        </select>
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Telefone*</label>
                        <input type="tel" class="form-control" id="phone" required data-validation-required-message="Por favor, insira seu número de telefone." placeholder="(00) 0000-0000">
                    </div>
                </div>
                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Email*</label>
                        <input type="email" class="form-control" id="email" required data-validation-required-message="Por favor, insira seu email.">
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">

                        <label style="padding-top:15px;"><i class="fa fa-calendar" aria-hidden="true"></i> Data de Nascimento</label>
                        <input type="date" class="form-control" id="date1">
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Endereço*</label>
                        <input type="text" class="form-control" id="endereco" required data-validation-required-message="Por favor, insira seu endereço.">
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>RG*</label>
                        <input type="text" class="form-control" id="rg" required data-validation-required-message="Por favor, insira seu RG.">
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Atleta de Natação?</label>

                        <select class="form-control" name="atleta">
                          <option value="volvo">Sim</option>
                          <option value="saab">Não</option>
                        </select>
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Profissional de Educação Física?</label>

                        <select class="form-control" name="profissional">
                          <option value="volvo">Sim</option>
                          <option value="saab">Não</option>
                        </select>
                    </div>
                </div>

                <div class="control-group form-group">
                    <div class="controls col-lg-12">
                        <label>Número do CREF (Apenas para Profissionais de Educação Física):</label>
                        <input type="text" class="form-control" id="cref">
                    </div>
                </div>






                <div class="control-group form-group">
                    <div class="controls col-lg-12">

                        <label>Mensagem</label>
                        <textarea rows="10" cols="100" class="form-control" id="message" maxlength="999" style="resize:none"></textarea>
                    </div>
                </div>

                </div><!--row-->



                 <div class="col-lg-12">


                <div id="success"></div>
                <!-- For success/fail messages -->
                <br>
                <button type="submit" class="btn btn-success btn-lg">Enviar</button>
                </div>


            </form>

Javascript to validate:

/*
  Jquery Validation using jqBootstrapValidation
   example is taken from jqBootstrapValidation docs 
  */
$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // something to have when submit produces an error ?
            // Not decided if I need it yet
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var tipo = $("select#tipo").val();
            var phone = $("input#phone").val();
            var email = $("input#email").val();
            var date1 = $("input#date1").val();
            var endereco = $("input#endereco").val();
            var rg = $("input#rg").val();
            var cref = $("input#cref").val();
            var atleta = $("select#atleta").val();
            var profissional = $("select#profissional").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "bin/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    tipo: tipo,
                    phone: phone,
                    email: email,
                    date1: date1,
                    endereco: endereco,
                    rg: rg,
                    atleta: atleta,
                    profissional: profissional,
                    cref: cref,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Sua inscrição foi enviada. Lembre-se de que é preciso realizar o pagamento online para efetivar a inscrição. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>" + firstName + " Parece que não está funcionando...</strong> Você poderia enviar um email direto para nós? Desculpe pela inconveniência.");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

PHP to send

<?php
if(empty($_POST['name'])        ||
   empty($_POST['phone'])       ||
   empty($_POST['email'])       ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }
$name = $_POST['name'];
$tipo = $_POST['tipo'];
$phone = $_POST['phone'];
$email_address = $_POST['email'];
$date1 = $_POST['date1'];
$endereco = $_POST['endereco'];
$rg = $_POST['rg'];
$atleta = $_POST['atleta'];
$profissional = $_POST['profissional'];
$cref = $_POST['cref'];
$message = $_POST['message'];

// create email body and send it    
$to = '[email protected]'; 
$email_subject = "Formulário de Inscrições, $name fez uma inscrição."; 
$email_body = "Uma inscrição foi realizada no site."."Aqui estão os detalhes:\n\nNome: $name\n\nTipo de inscrição: $tipo\n\nTelefone: $phone\n\nData de Nascimento: $date1\n\nEndereço: $endereco\n\nRG: $rg\n\nEmail: $email_address\n\nAtleta de Natação? $atleta\n\nProfissional de Educação Física? $profissional\n\nCREF: $cref\n\nMensagem:\n$message";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>

At the moment I receive very well by email all information that is not select, those of the select element are empty.

  • With select is the same as with inputs

  • Add the "ID" attribute to your select or use $("select[name=\"tipo\"]").val();

1 answer

0

You need to do 3 things

1 - adjust selectors of selects

var tipo = $("select[name='tipo']").val();<br>
var atleta = $("select[name='atleta']").val();<br>
var profissional = $("select[name='profissional']").val();

And the values of the athletic and professional fields are "Volvo and Saab", via really want to pass these values?

follows the correct script:

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // something to have when submit produces an error ?
            // Not decided if I need it yet
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var tipo = $("select[name='tipo']").val();
            var phone = $("input#phone").val();
            var email = $("input#email").val();
            var date1 = $("input#date1").val();
            var endereco = $("input#endereco").val();
            var rg = $("input#rg").val();
            var cref = $("input#cref").val();
            var atleta = $("select[name='atleta']").val();
            var profissional = $("select[name='profissional']").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "bin/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    tipo: tipo,
                    phone: phone,
                    email: email,
                    date1: date1,
                    endereco: endereco,
                    rg: rg,
                    atleta: atleta,
                    profissional: profissional,
                    cref: cref,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Sua inscrição foi enviada. Lembre-se de que é preciso realizar o pagamento online para efetivar a inscrição. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>" + firstName + " Parece que não está funcionando...</strong> Você poderia enviar um email direto para nós? Desculpe pela inconveniência.");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.