Search code examples
javascriptphparrayscheckboxcontact-form

Passing checkbox array for PHP email using Javascript validation


I have a form with two checkbox arrays that I need to pass to a PHP email script. The form data goes through validation with a javascript function before being sent to the PHP script... I am struggling to get the array to into my form data here is one of my checkbox arrays

                 <div class="choice-group">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="choice">
                                    <input type="checkbox" id="low" name="budgetvar[]" value="low">
                                    <label for="low">Low Cost</label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="choice">
                                    <input type="checkbox" id="medium" name="budgetvar[]" value="medium">
                                    <label for="medium">Medium Range</label>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="choice">
                                    <input type="checkbox" id="premuim" name="budgetvar[]" value="premuim">
                                    <label for="premuim">Premium Range</label>
                                </div>
                            </div>

                        </div>
                    </div>

And here is my Javascript formData

formData = {
            'firstname': $('input[name=firstname]').val(),
            'lastname': $('input[name=lastname]').val(),
            'phone': $('input[name=phone]').val(),
            'email': $('input[name=email]').val(),
            'consent': $('input:checkbox[name=consent]').is(':checked'),
            'budgetvar': $('input:checkbox[name=budgetvar]').val(),
            'optionsvar': $('input:checkbox[name=optionsvar]').val(),
            'message': $('textarea[name=message]').val()

        };

Here is my .ajax code

$.ajax({
            url: "includes/mail/mail.php",
            type: "POST",
            data: formData,
            success: function(data, textStatus, jqXHR) {

                $('#status').text(data.message);
                if (data.code) //If mail was sent successfully, reset the form.
                    $('#contact-form').closest('form').find("input[type=text], textarea").val("");
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $('#status').text(jqXHR);
            }
        });

I then look to get the variables in my PHP script as follows

$budget = implode(', ', $_POST['budgetvar']);

Any help on how to get these values into an array I can then use through a php email would be a massive help! I have looked on here but I can't seem to find anything that I can try and manipulate to fix my problem.. Relatively new to this so complex solutions seem to go over my head a little bit

Thanks in advance!


Solution

  • Just use the built-in FormData object to collect all the data:

    formData = new FormData( document.querySelector("form") );
    

    The browser can do all the collection for you. You don't need to pick out each form control one-by-one.

    If you set send that using .ajax make sure you set processData: false; contentType: false to stop jQuery trying to be clever (which will break that natural cleverness of XMLHttpRequest).


    If you really wanted to do this manually then you would need to:

    1. Find all the checked inputs (using their real name, which has a [] on the end)
    2. Get their values
    3. Put them into an array

    e.g.

    'budgetvar': $('input[name="budgetvar[]"]:checked').map(
        (index, element) => element.value
     ).get()