problems submitting form

Asked

Viewed 90 times

0

Guys I developed a form on this website in php and javascript it has a select Multiple where the user will be able to select more than one value when sending my form it arrives with all the information but where there is select Multiple it does not appear anything this and the line where will have the array

 <select id="select-picker" class="selectpicker config" multiple
         name="config[]" id="config" data-selected-text-format="count > 3" 
         title="Configurações do evento"> 



<select id="select-picker" class="selectpicker" multiple
         data-selected-text-format="count > 3" title="Selecione os equipamentos"
         name="equip[]" id="equip" required>

the point here is that I don’t know how to make the call from these tags name="config[]" or name="equip[]" for example in my php code or javascript someone could help me follow the project codes:

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" selected>Mesas e cadeiras</option>
                                    <option value="Auditório" selected>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(); 
    //console.log(user_config);
    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');

    }
});

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       =           $_POST["userConfig"];
    $user_Quant =                  $_POST["userQuant"];
    $user_Equip       =            $_POST["userEquip"];
    //$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);
    }
}
?>
  • 1

    I may be wrong, but it doesn’t seem right to use [] in the ids...

  • thanks for the comment I already edited the question was performing some tests in the code and forgot to remove from the friendliest id you managed to understand my question in the question ? I need to finish this today and have no idea how to make the name call="config[]" in my js and php code

  • 1

    try using $("#form-Elements"). serialize(); instead of post_data = {'username... and see what comes of results in your php, using var_dump or print_r

  • é para eu colocar so esse código no lugar desse post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip};

  • exactly. It will look like this: var post_data = $("#form-Elements"). serialize();

  • I believe your error is when you take the value of the form and pass to the post_data variable and the ajax

  • @Kirito if the value of the config and Equip variables appears in the PHP var_dump, let me know to post it as a response and explain it to someone who might have the same question. hugs

  • @DiegoAndrade amigo eu comentei essa linha inteira post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userDate':user_date, 'userConfig':user_config, 'userQuant':user_quant, 'userEquip':user_equip}; and I will add the code you sent above var post_data = $("#form-Elements"). serialize(); and I’ll see the result

  • @Diegoandrade if I edit the code the way you gave it to me it falls into this error that is in php $output = json_encode(array('type'=>'error', 'text' => 'The input fields are empty! '));

  • Kirito, edit php, put in the first line the following code snippet: var_dump($_POST); die; open your browser console, look in the console what php returned and paste here

  • @Diegoandrade puts this before the opening of the <?php tag

  • appeared this XHR finished loading: GET "https://www.google.com/maps/vt?pb=! 1m4! 1m3! 1i16! 2i24269! 3i37182! 1m4! 1m3! 1i1... ity_class! 2s0! 12m1! 1e68!12m3! 1e37!2m1! 1ssmartmaps! 4e3!12m1! 5b1&token=59946". (Anonymous) @VM193:1 eh @util.js:142 _. Fh @ util.js:142 (Anonymous) @ Onion.js:19 Iw.load @ Onion.js:65 [email protected]:23 Jw. l @Onion.js:65

  • after opening the <php tag?.

  • @Kirito the location you will check this return of the post, is when you open the "inspect element", in the network tab. There, will appear the requests that your site is making. Click on the page contact.php. which is the one that ajax makes the request, and go to "Answer". There, you should print the print_r($_POST) result. That’s what I need

  • @Diegoandrade array(7) { ["username"]=> string(21) "Felipe Henrique silva" ["userEmail"]=> string(29) "[email protected]" ["userPhone"]=> string(14) "(11) 43710-555" ["userDate"]=> string(10) "21/32/1231" ["userConfig"]=> array(2) { [0]=> string(14) "Tables-Chairs" [1]=> string(10) "Auditorium" } ["userQuant"]=> string(6) "555555" ["userEquip"]=> array(2) { [0]=> string(8) "Projector" [1]=> string(10) "Flip-Chart" } }

  • in the var dump I sent you above it appeared all the instructions because in my html tag name="config[]" I removed these conchetes and when redoing the test with the conchetes it looks like it looked like array(5) { ["username"]=> string(21) "Felipe Henrique silva" ["userEmail"]=> string(29) "[email protected]" ["userPhone"]=> string(14) "(11) 43710-555" ["userDate"]=> string(10) "55/55/5555" ["userQuant"]=> string(3) "666" }

  • @Kirito if my answer is correct, if you can mark as the correct answer I thank you! hugs and hope to have helped

  • @Diegoandrade friend I comment below your answer you came to take a look ? ta giving a little problem

Show 13 more comments

2 answers

2

Look, in PHP will not make the slightest difference as you call the select, even because you are doing a post with the data of this form.

If you take a look at the fiddle below, basically I replicated the code of one of your selects and put a very simple JS to print what it produces at the end:

$('button').on('click', function(e) {
  console.log($('#select-picker option:selected'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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" selected>Mesas e cadeiras</option>
                                    <option value="Auditório" selected>Auditório</option>
                                    <option value="Lounge">Lounge</option>
                                    <option value="Galeria">Galeria</option>
                                </select>
<button type="button">
ok</button>

See that it prints an array of objects, whose first two elements are the elements you have selected, so since you already have an ID in your element, then you can just iterate through the values more or less like this:

$('button').on('click', function(e) {
  var selected = $('#select-picker option:selected')
  
  for(var i = 0; i < selected.length; i++) {
    console.log(selected[i].value)
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <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" selected>Mesas e cadeiras</option>
                                        <option value="Auditório" selected>Auditório</option>
                                        <option value="Lounge">Lounge</option>
                                        <option value="Galeria">Galeria</option>
                                    </select>
    <button type="button">
    ok</button>

Only that you mount an array with the values and send it by post to PHP, you will receive an array on the other side and can handle it the way you want.

1


The error is in setting the js variable "post_data" with the data you sent by ajax.

//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};

after all the validations that have been made above that, as you will use all the form fields to submit to ajax, you can use the serialize(),

var post_data = $("#form-elements").serialize();

which takes all form fields and transforms into a string with input names and values in encoded object format. So, you will send by ajax and will be able to work with the desired information there.

Edit: Then, changing the names of the variables to the names respectively sent, both in the validation, and in the assignment of the values, should work. To transform the array into a string, do it this way? replace the 2 lines where you assign the user_Config and user_Equip variables so:

$user_Config       =           implode(", ",$_POST["config"]);   
$user_Equip       =            implode(", ",$_POST["equip"]);

hugs

  • friend doing this he falls into an error in my php that is on that line if(!isset($_POST["username"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userDate"]) || !isset($_POST["userQuant"]) { $output = json_encode(array('type'=>'error', 'text' => 'The input fields are empty! '); die($output); } ?

  • I believe this is the answer I need to know now because it only falls in this condition when I edit my code for the one you sent it only falls in the condition mentioned access the site where the form you see the error

  • I added a var dump just below if(!isset($_POST["username"] ....) to see what appears on the console array(7) { ["name"]=> string(21) "Felipe Henrique silva" ["email"]=> string(29) "[email protected]" ["phone"]=> string(14) "(11) 43710-555" ["date"]=> string(10) "23/45/4235" ["config"]=> array(2) { [0]=> string(10) "Auditorium" [1]=> string(6) "Lounge" } ["Quant"]=> string(6) "666666" ["Equip"]=> array(2) { [0]=> string(8) "Projector" [1]=> string(3) "Sound" } }

  • opa, sorry @Kirito, had not seen. You gave var_dump($_POST) and he returned this data following?? array(7) { ["name"]=> string(21) "Felipe Henrique silva" ["email"]=> string(29) "[email protected]" ["phone"]=> string(14) "(11) 43710-555" ["date"]=> string(10) "23/45/4235" ["config"]=> array(2) { [0]=> string(10) "Auditorium" [1]=> string(6) "Lounge" } ["Quant"]=> string(6) "666666" ["Equip"]=> array(2) { [0]=> string(8) "Projector" [1]=> string(3) "Sound" } }

  • if so, check the name of the variables you are sending, with the names of the variables that are in condition. They must be identical: if(! isset($_POST["username"]) || ! isset($_POST["userEmail"]) || ! isset($_POST["userPhone"]) || ! isset($_POST["userDate"]) || ! isset($_POST["userQuant"]))

  • friend in case the variables that are within my if have to be equal to the ones that gave in the vardump

  • getting so if(! isset($_POST["name"]) || ! isset($_POST["email"]) || ! isset($_POST["phone"]) || ! isset($_POST["date"]) || ! isset($_POST["Quant"]))

  • 1

    exactly. It worked?

  • Can I add you friend on facebook or skype for you to take a closer look? it stopped falling in that condition and sending normal but still do not receive in the email the fields that has the selectpicker

  • 1

    skype diegosalamex

  • I’ll just add

  • I already sent the request

Show 8 more comments

Browser other questions tagged

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