简体   繁体   中英

Get checked checkboxes values from a form with ajax

Just trying to learn by myself how to make a form and I'm currently stuck with checkboxes.

When submitting, my form is sending an mail to a specific address (currently working).

However, I cannot get all the checked checkboxes values selected by user; I get 'undefined' in my mail. Please see as below my html/js/php part of code. Please be as simple as possible as I am a full begginer.

HTML

    <!-- Start Contact -->
    <div id="contact" class="contact-box">
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="title-box">
                        <h2>Confirmez-nous votre présence</h2>
                        <p>On a hâte d'y être. Et vous ? </p>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-lg-12 col-sm-12 col-xs-12">
                  <div class="contact-block">
                    <form method="POST" action="form-process.php" id="contactForm">
                      <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <input type="text" class="form-control" id="name" name="name" placeholder="Nom & Prénom" required data-error="Merci d'entrer votre nom et prénom.">
                                <div class="help-block with-errors"></div>
                            </div>                                 
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <input type="text" placeholder="Adresse mail" id="email" class="form-control" name="email" required data-error="Merci d'entrer votre adresse mail.">
                                <div class="help-block with-errors"></div>
                            </div> 
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <select class="custom-select d-block form-control" id="adulte" name="adulte" required data-error="Merci d'indiquer le nombre d'invités adultes.">
                                  <option disabled selected value>Nombre d'invités adultes*</option>
                                  <option value="1">Juste moi !</option>
                                  <option value="2">2</option>
                                  <option value="3">3</option>
                                  <option value="4">4</option>
                                  <option value="5">5</option>
                                </select>
                                <div class="help-block with-errors"></div>
                            </div> 
                        </div>
                        <div class="col-md-12">
                            <div class="form-group">
                                <select class="custom-select d-block form-control" id="enfant" name="enfant" required data-error="Merci d'indiquer le nombre d'invités enfants.">
                                  <option disabled selected value>Nombre d'invités enfants*</option>
                                  <option value="Aucun">Aucun !</option>
                                  <option value="1">1</option>
                                  <option value="2">2</option>
                                  <option value="3">3</option>
                                  <option value="4">4</option>
                                </select>
                                <div class="help-block with-errors"></div>
                            </div> 
                        </div>
                        <div class="col-md-12">
                        <div class="form-group">
                        Je serai présent(e) / Nous serons présent(e)s :*
                         <table class="form-control" style="background-color: #e6eceb; height: 210px" id="event">
                         <tr>
                           <td><label>
                             <input type="checkbox" name="choice[]" value="mairie" id="CheckboxGroup1">
                             Cérémonie civile</label></td>
                           </tr>
                         <tr>
                           <td><label>
                             <input type="checkbox" name="choice[]" value="vin d'honneur" id="CheckboxGroup2">
                             À la santé des mariés !</label></td>
                           </tr>
                         <tr>
                           <td><label>
                             <input type="checkbox" name="choice[]" value="église" id="CheckboxGroup3">
                             Cérémonie religieuse</label></td>
                           </tr>
                         <tr>
                           <td><label>
                             <input type="checkbox" name="choice[]" value="dîner" id="CheckboxGroup4">
                             Dîner</label></td>
                           </tr>
                         <tr>
                           <td><label>
                             <input type="checkbox" name="choice[]" value="brunch" id="CheckboxGroup5">
                             Brunch BBQ</label></td>
                           </tr>
                         <tr>
                           <td><label>
                             <input type="checkbox" name="choice[]" value="aucun" id="CheckboxGroup6">
                             Malheureusement indisponible(s)</label></td>
                           </tr>
                         </table>
                                                </div>
                           </div>
                        <div class="col-md-12">
                            <div class="form-group"> 
                                <textarea class="form-control" id="message" name="msg" placeholder="Une information à nous communiquer ? Le nom des gens accompagnant ? Végan, végétarien ou simplement au régime ?" rows="8" data-error="Une information à nous communiquer ? Le nom des personnes accompagnatrices ? Végan, végétarien ou simplement au régime ? Une musique qui vous ambiance ?" ></textarea>
                                <div class="help-block with-errors"></div>
                            </div>
                            <div class="submit-button text-center">
                                <button class="btn btn-common" id="submit" type="submit">Envoyer la confirmation</button>
                                <div id="msgSubmit" class="h3 text-center hidden"></div> 
                                <div class="clearfix"></div> 
                            </div>
                        </div>
                      </div>            
                    </form>
                  </div>
                </div>
            </div>
        </div>
    </div>
    <!-- End Contact -->

Javascript

$("#contactForm").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        // handle the invalid form...
        formError();
        submitMSG(false, "Le formulaire est incomplet.");
    } else {
        // everything looks good!
        event.preventDefault();
        submitForm();
    }
});


function submitForm(){
    // Initiate Variables With Form Content
    //var name = $("#name").val();
    //var email = $("#email").val();
    //var msg_subject = $("#msg_subject").val();
    //var message = $("#message").val();
    //var adulte = document.getElementById('adulte').value;
    //var enfant = document.getElementById('enfant').value;
    
    var formData = new FormData(event.target);
    var checkedOnes = formData.getAll("choice[]");
    var name = formData.get("name");
    var email = formData.get("email");
    var message = formData.get("msg");
    var adulte = formData.get("adulte");
    var enfant = formData.get("enfant");
    var data = { name, email, message, adulte, enfant, checkedOnes: checkedOnes.toString() };

    $.ajax({
        type: "POST",
        url: "php/form-process.php",
        //data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message + "&adulte=" + adulte + "&enfant=" + enfant + "&choice=" + strChkOnes,
        data: data,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                formError();
                submitMSG(false,text);
            }
        }
    });
}

function formSuccess(){
    $("#contactForm")[0].reset();
    submitMSG(true, "Message envoyé !")
}

function formError(){
    $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
        $(this).removeClass();
    });
}

function submitMSG(valid, msg){
    if(valid){
        var msgClasses = "h3 text-center tada animated text-success";
    } else {
        var msgClasses = "h3 text-center text-danger";
    }
    $("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}

PHP

<?php

$errorMSG = "";

// NAME
if (empty($_POST["name"])) {
    $errorMSG = "Nom et prénom requis ";
} else {
    $name = $_POST["name"];
}

// EMAIL
if (empty($_POST["email"])) {
    $errorMSG .= "Email requis ";
} else {
    $email = $_POST["email"];
}

// MSG Guest
if (empty($_POST["adulte"])) {
    $errorMSG .= "Nombre d'invités adultes requis ";
} else {
    $adulte = $_POST["adulte"];
}

if (empty($_POST["enfant"])) {
    $errorMSG .= "Nombre d'invités enfants requis ";
} else {
    $enfant = $_POST["enfant"];
}

// MSG Event
//if (empty($_POST["event"])) {
//    $errorMSG .= "Détails de votre présence requis ";
//} else {
//    $event = $_POST["event"];
//}
$checkedOnes = $_POST["checkedOnes"];

// MESSAGE
//if (empty($_POST["message"])) {
//    $errorMSG .= "Message is required ";
//} else {
//    $message = $_POST["message"];
//}
$message = $_POST["message"];


$EmailTo = "xxx@gmail.com";
$Subject = "Nouvelle confirmation de présence";

// prepare email body text
$Body = "";
$Body .= "Nom : ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email : ";
$Body .= $email;
$Body .= "\n";
$Body .= "Adulte(s) : ";
$Body .= $adulte;
$Body .= "\n";
$Body .= "Enfant(s) : ";
$Body .= $enfant;
$Body .= "\n";
$Body .= "Présent(s) à : ";
$Body .= $checkedOnes;
$Body .= "\n";
$Body .= "Message : ";
$Body .= $message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);

// redirect to success page
if ($success && $errorMSG == ""){
   echo "success";
}else{
    if($errorMSG == ""){
        echo "Un problème est survenu :(";
    } else {
        echo $errorMSG;
    }
}

?>

Currently, the mail looks perfect except that, next to 'event :' I got undefined... :'(

I think you should use a form instead of a table. Check also the formSubmit function in this example for how to get the values from the form. I have tested the belowe example and it works. In the PHP code you can get all the posted values ith $_POST["name"] , $_POST["email"] , $_POST["checkedOnes"] :

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script
      src="https://code.jquery.com/jquery-3.5.1.min.js"
      integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
      crossorigin="anonymous"
    ></script>
  </head>

  <body>
    <div id="app"></div>
    <div class="form-group">
      Je serai présent(e) / Nous serons présent(e)s :*
      <form onsubmit="formSubmit()">
        <label for="form-name">Name</label>
        <input type="textbox" id="form-name" name="name" /><br />
        <label for="form-email">Email</label>
        <input type="email" id="form-email" name="email" /><br />
        <input
          type="checkbox"
          name="choice[]"
          value="mairie"
          id="CheckboxGroup1"
        />
        <label for="CheckboxGroup1">Cérémonie civile</label><br />
        <input
          type="checkbox"
          name="choice[]"
          value="vin d'honneur"
          id="CheckboxGroup2"
        />
        <label for="CheckboxGroup2">À la santé des mariés !</label><br />
        <input type="submit" />
      </form>
    </div>
    <script>
      function formSubmit() {
        event.preventDefault();
        var formData = new FormData(event.target);
        var checkedOnes = formData.getAll("choice[]");
        var name = formData.get("name");
        var email = formData.get("email");
        console.log(checkedOnes, name, email);
        var data = { name, email, checkedOnes: checkedOnes.toString() };
        $.ajax({
          type: "POST",
          url: "./php/form-process.php",
          data: data
        });
      }
    </script>
  </body>
</html>

It does not help checking for the isChecked attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/checkbox

Update I have checked you latest code and there are at least two problems:

1 The HTML form:

<form method="POST" action="form-process.php" id="contactForm">

This way, when the user clicks submit , you are sending directly a POST message to form-process.php , instead of calling the submitForm() function, which in turns would collect the necessary form data and send it to form-process.php .

So you should change the line to:

<form onsubmit="submitForm()" id="contactForm">

This way the form data will be sent to the submitForm function which will extract the data and post it to form-process.php .

2 Another problem is that you are missing event.preventDefault(); from the beginning of the submitForm function, without it the page will be reloaded and the code will not be executed. So it should be:

function submitForm(){ 
    event.preventDefault();
    var formData = new FormData(event.target);
    var checkedOnes = formData.getAll("choice[]");
    // Then the rest of your code

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