Problem with select Multiple in form

Asked

Viewed 659 times

0

I developed a website where you will have a form where you will receive an email inside that form exite 2 inputs select however the user will be able to select more than one option so I added the tag multiple soon it will be able to select more than one field when submitting the form it usually works but it does not receive the other options of my select If I select more than one option in the email only appears one and the others do not, I wonder how I can make appear the other options in the email follows the image of how it is displayed in the email and the codes. You can notice on the site I selected more than one option and in the email that arrives only one of them appears.

inserir a descrição da imagem aqui

HTML:

<form class="form-budget" id="form-elements" onSubmit="return false">
                            <div class="row">
                                <div class="col-md-12 center">
                                    <div id="result"></div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <input type="text" placeholder="Digite seu nome" name="name" id="name" required/>
                                <input type="text" placeholder="Digite seu Email" name="email" id="email" required/>
                                <input type="tel" placeholder="Digite seu Telefone" name="phone" id="phone" class="phone_with_ddd" required/>
                                <input type="text" placeholder="Data do evento" name="date" id="date" class="date" required/>
                            </div>

                            <div class="col-md-6">
                                <select id="select-picker" class="selectpicker config" multiple
                                        name="config" id="config"
                                        data-selected-text-format="count > 3" title="Configurações do evento">
                                    <option value="Mesas-Cadeiras">Mesas e cadeiras</option>
                                    <option value="Auditório">Auditório</option>
                                    <option value="Lounge">Lounge</option>
                                    <option value="Galeria">Galeria</option>
                                </select>
                                <input type="text" placeholder="Quantidade de pessoas" name="quant" id="quant" class="quant" required/>

                                <select id="select-picker" class="selectpicker" multiple
                                        data-selected-text-format="count > 3" title="Selecione os equipamentos"
                                        name="equip" id="equip" required>
                                    <option value="Projetor">Projetor</option>
                                    <option value="Som">Caixa de som</option>
                                    <option value="Flip-Chart">Flip-Chart</option>
                                </select>
                                <button type="submit" class="btn btn-success" id="submit_btn">Enviar orçamento</button>
                            </div>
                        </form>

JS:

//Contact Us
$("#submit_btn").click(function() {
    //get input field values
    var user_name       = $('input[name=name]').val();
    var user_email      = $('input[name=email]').val();
    var user_phone      = $('input[name=phone]').val();
    var user_date       = $('input[name=date]').val();
    var user_config     = $('select[name=config] option:selected').val();
    var user_quant      = $('input[name=quant]').val();
    var user_equip      = $('select[name=equip] option:selected').val();
    //var user_message    = $('textarea[name=message]').val();

    //simple validation at client's end
    var post_data, output;
    var proceed = true;
    if(user_name==""){
        proceed = false;
    }
    if(user_email==""){
        proceed = false;
    }
    if(user_phone=="") {
        proceed = false;
    }

    if(user_quant=="") {
        proceed = false;
    }
    if(user_date=="") {
        proceed = false;
    }

    //everything looks good! proceed...
    if(proceed)
    {
        //data to be sent to server
        post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip};

        //Ajax post data to server
        $.post('contact.php', post_data, function(response){

            //load json data from server and output message
            if(response.type == 'error')
            {
                output = '<div class="alert-danger" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';
            }else{
                output = '<div class="alert-success" style="padding:10px; margin-bottom:25px;">'+response.text+'</div>';

                //reset values in all input fields
                $('#form-elements input').val('');
                $('#form-elements textarea').val('');
            }

            $("#result").hide().html(output).slideDown();
        }, 'json');

    }
});

//reset previously set border colors and hide all message on .keyup()
$("#form-elements input, #form-elements textarea").keyup(function() {
    $("#result").slideUp();
});

PHP:

<?php
if($_POST)
{
    $to_Email       = "[email protected]"; //Replace with recipient email address
    $subject        = 'Orçamento do site'; //Subject line for emails


    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error',
            'text' => 'Request must come from Ajax'
        ));

        die($output);
    }

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userDate"]) || !isset($_POST["userQuant"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Os campos de entrada estão vazios!  '));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone =                  $_POST["userPhone"];
    $user_Date =                  $_POST["userDate"];
    $user_Config       = filter_var($_POST["userConfig"], FILTER_SANITIZE_EMAIL);
    $user_Quant =                  $_POST["userQuant"];
    $user_Equip       = filter_var($_POST["userEquip"], FILTER_SANITIZE_EMAIL);
    //$user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'O campo nome não pode ficar vazio'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor ultilize um e-mail válido'));
        die($output);
    }

    if(strlen($user_Phone)<5) //check emtpy phone
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira um número de telefone'));
        die($output);
    }


    if(strlen($user_Date)<5) //check emtpy date
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira uma data para o evento'));
        die($output);
    }

     if(strlen($user_Quant)<2) //check emtpy date
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Por favor insira a quantidade de pessoas para o evento'));
        die($output);
    }


    $message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
    $message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
    $message_Body .= "<strong>Phone: </strong>". $user_Phone ."<br>";
    $message_Body .= "<strong>Data do Evento: </strong>". $user_Date ."<br>";
    $message_Body .= "<strong>Quantidade de pessoas: </strong>". $user_Quant ."<br>";
    $message_Body .= "<strong>Configurações do evento: </strong>". $user_Config ."<br>";
    $message_Body .= "<strong>Equipamentos: </strong>". $user_Equip ."<br>";
    //$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";



    $headers = "From: " . strip_tags($user_Email) . "\r\n";
    $headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";



    //proceed with PHP email.
    $headers = 'From: '.$user_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion(). "\r\n" .
    'Content-type: text/html;charset=UTF-8';



    $sentMail = @mail($to_Email, $subject, $message_Body, $headers);

    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Ocorreu um erro tente novamente'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Olá '. $user_Name .' Obrigado pelo seu contato retornaremos em breve.'));
        die($output);
    }
}
?>

console log.inserir a descrição da imagem aqui

  • Have you tried without the option:selected in selectors of selects? Without this will return an array only with the selected values.

  • @Killerjack if I take this part of the code returns empty in the email

  • 1

    Place console.log(user_config); after the variable declaration in javascript and see the result with and without the option:selected. The problem of being empty should be because it is now an array and has no loop in its code to traverse it.

  • 1

    var_dump displays the content on the screen, not in devtools. console.log yes, appears in devtools.

  • would be so friend var user_config = console.log('select[name=config] option:Selected'). val(); is correct ?

  • 1

    No, do not modify the variable definition. Just add console.log(user_config); in another row, below the one that defines the variable and see what appears in devtools.

  • Ready friend I put in question la google console and the line where I inserted the console

  • Friend I did better I added the line of code that you sent straight to the console and printei and added in the question gave Undefined

  • You need to select things in select in order to see the value. In the image it is Undefined because you have not selected anything. Take the test I said: Select two or more values with the option:selected and see that only the last one will appear, then take out the option:selected and do the same test, you will see that will show all in an array.

  • @Killerjack Amigo I added Selected to my code and ran the n console command and still gave error on the console it appears that VM96:1 Uncaught Referenceerror: user_config is not defined at <Anonymous>:1:13 sound the without Selected when running the error command

Show 5 more comments

1 answer

1

You must declare the select name as an array:

<select multiple name="config[]"></select>

To transform the received array into a string you can use the function implode().

  • when declaring it as array the name that was there to lose the references in the code to call this array in js and php how do ? sorry for the question I’m beginner in programming

  • 1

    In js you may not need to change. Check the config value in php with var_dump($_POST['config']); die;

  • would look like this my code in php $user_Config = var_dump($_POST["userConfig"], FILTER_SANITIZE_STRING);

  • The var_dump would be just for you to check the value that JS is sending to PHP.

  • I’ll check here and I’ll add the console print of the question for you to analyze

  • I added the console print to the question if you can take a look at my php code added this line $user_Config = var_dump($_POST["userConfig"], FILTER_SANITIZE_STRING);

  • 1

    You don’t need to and should not actually add var_dump to a variable. Simply run the command and see what appears on the screen and not in devtools.

  • @Killerjack I added name="config[]" then in my options I left with Selected so that on the site show already selected field and when I run the command in the browser console appears the error Uncaught Referenceerror: var_dump is not defined at <Anonymous>:1:1

  • 1

    See the documentation of var_dump()

  • @Rayannnayran this is the command I’m running on the var_dump($_POST['config']) console; the config in this case would be the array I’m using in my selectpicker in the case it was named="config[]" this in the above answer but only an error appears in the cosole and does not return any value

  • var_dump() is PHP, you should not run it on the console, but write it in your code.

Show 6 more comments

Browser other questions tagged

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