2

I have a pet registration form where people can add a new pet.

People will click the add pet button and jquery clones the pet portion of the form and changes the id to #pet-2, another, #pet-3 and so on.

After fruitless web searching, I now need to know how to send this via php and ajax.

I have already created an ajax function for my contact forms as well as have php code to send the contact forms so would, ideally, want to modify that code in a separate file to handle the register pet also.

Here is the fiddle: http://jsfiddle.net/zsxe44c8/

Here is the code for the add pet form:

<form id="register-pet-form" data-quantity="1">

            <fieldset id="practiceField" class="row">

                <div class="col-md-6 push-md-6">

                    <h3>Practice</h3>

                    <select name="practice">
                        <option value="">Value 1</option>
                        <option value="">Value 2</option>                    
                    </select>

                </div>

            </fieldset>
            <!--/#practiceField-->

            <fieldset id="ownerDetails" class="row">

                <div class="col-md-6">

                    <h3>Your details</h3>
                    <select name="title">
                        <option value="Mr">Mr</option>
                        <option value="Mrs">Mrs</option>
                        <option value="Miss">Miss</option>
                        <option value="Ms">Ms</option>
                        <option value="Dr">Dr</option>
                        <option value="Prof">Prof</option>
                    </select>

                    <input name="fname" type="text" placeholder="First Name">

                    <input name="lname" type="text" placeholder="Last Name">

                    <input name="number" type="text" placeholder="Contact Number">

                    <input name="email" type="text" placeholder="Email Address">

                </div>

                <div class="col-md-6">

                    <h3>Your Address</h3>

                    <input name="address1" type="text" placeholder="Address 1">

                    <input name="address2" type="text" placeholder="Address 2">

                    <input name="address3" type="text" placeholder="Address 3">

                    <input name="postcode" type="text" placeholder="Postcode">

                </div>

            </fieldset>
            <!--/#ownerDetails-->

            <fieldset id="pet-1" class="row">

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

                    <h3>Pet Details</h3>

                </div>

                <div class="col-md-6">

                    <input name="pet-name" type="text" placeholder="Pet Name">

                    <input name="pet-breed" type="text" placeholder="Pet Breed">

                    <input name="pet-age" type="text" placeholder="Age of pet">

                </div>

                <div class="col-md-6">

                    <select name="petGender">
                        <option value="Female">Female</option>
                        <option value="Male">Male</option>
                    </select>

                    <select name="petType">
                        <option value="Dog">Dog</option>
                        <option value="Cat">Cat</option>
                        <option value="Rabbit">Rabbit</option>
                        <option value="Gerbil">Gerbil</option>
                        <option value="Guinea Pig">Guinea Pig</option>
                        <option value="Hamster">Hamster</option>
                        <option value="Mouse">Mouse</option>
                        <option value="Rat">Rat</option>
                        <option value="Chinchilla">Chinchilla</option>
                        <option value="Other">Other</option>
                    </select>

                </div>

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


                    <input name="pet-desc" type="text" placeholder="Pet Description">

                    <textarea name="additional-comments" placeholder="Additional Comments"></textarea>


                </div>

            </fieldset>
            <!--#petDetails-->

            <div id="form-tools" class="row">

                <div class="col-md-6">

                    <a class="add-pet" href="#">Add another pet</a>

                </div>

                <div class="col-md-6 right">

                    <input type="submit" value="Submit">

                </div>

            </div>
            <!--/#form-tools-->

        </form>

Here is the jQuery code for the add pet form:

function registerPet() {

    function addPetRegistrationForm() {
        var container = $('#register-pet-form'),
            lastForm = $('#register-pet-form fieldset:last-of-type'),
            currentForm = $('#pet-1'),
            newForm = currentForm.clone(),
            currentVal = parseInt(container.attr('data-quantity'), 10),
            newVal = currentVal + 1;

        $('h3', newForm).after('<a data-id="' + newVal + '" class="js-remove-pet remove-pet" href="#">Remove this pet</a>');

        $('input, select', newForm).each(function () {

            var newId = this.id.substring(0, this.id.length - 1) + newVal;

            $(this).prev().attr('for', newId);

            this.name = this.id = newId;
        });

        lastForm.after(newForm.attr('id', 'pet-' + newVal));
        container.attr('data-quantity', newVal);
    }

    function removePetRegistrationForm(target) {
        $('#pet-' + target).remove();
    }

    function handleRegisterPet() {

        if($('#pet-1').length) {

            $('#pet-1').addClass('ispet');

            $('#pet-1 *[name]').each(function(){

                $(this).attr('name',$(this).attr('name') + '[]');
            });

            var newBlock = $('#pet-1').html();

            $('#pet-1').after('<a href="" class="form-button-2" id="js-add-pet">Add another pet</a>');

            $('.add-pet').on('click',function() {

                var count = $('.ispet').length + 1;

                $('.ispet').last().after('<fieldset id="pet-'+ count +'" class="ispet">' + newBlock + '</fieldset>');

                return false;

            });
        }
    }

    $('.add-pet').on('click', function () {
        addPetRegistrationForm();
        return false;
    });

    $('#register-pet-form').on('click', '.js-remove-pet', function () {
        removePetRegistrationForm($(this).attr('data-id'));
        return false;
    });
}

Now here is the code for the ajax contact form that is working and I wish to modify for the add pet form:

function ajaxForm(formID) {
    var form = $(formID);
    var formMessages = $('#form-messages');
    $(formMessages).hide();
    $(form).submit(function(event) {
        event.preventDefault();
        var formData = $(form).serialize();
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function() {
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            $(form).hide();
            $('#fname').val('');
            $('#lname').val('');
            $('#email').val('');
            $('#phone').val('');
            $('#message').val('');
            $(formMessages).html(
                '<div class="alert alert-success" role="alert"><i class="fa fa-check"></i> <strong>Your message has been sent successfully</strong></div>'
            ).fadeIn();

        })
        .fail(function() {
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });
    });

}

function practiceOneContact() {
    ajaxForm('#practice-1-contact-form');
}
function practiceTwoContact() {
    ajaxForm('#practice-2-contact-form');
}
function practiceThreeContact() {
    ajaxForm('#practice-3-contact-form');
}
function practiceFourContact() {
    ajaxForm('#practice-4-contact-form');
}

And finally, the PHP code for the contact form handler that I wish to modify to allow for dynamic pets from the add pet form:

<?php

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $fname = strip_tags(trim($_POST["fname"]));
                $fname = str_replace(array("\r","\n"),array(" "," "),$fname);
        $lname = strip_tags(trim($_POST["lname"]));
                $lname = str_replace(array("\r","\n"),array(" "," "),$lname);
        $phone = strip_tags(trim($_POST["phone"]));
                $phone = str_replace(array("\r","\n"),array(" "," "),$phone);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);
        $sendTo = strip_tags(trim($_POST["sendTo"]));
        $practice = trim($_POST["practice"]);

        echo 'field editing done';

        // Check that data was sent to the mailer.
        if ( empty($fname) OR empty($lname) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        $recipient = $sendTo;

        // Set the email subject.
        $subject = "New contact from $fname $lname";

        // Build the email content.
        $email_content = "Practice Name: $practice\n";
        $email_content .= "First Name: $fname\n";
        $email_content .= "Last Name: $lname\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Phone: $phone\n\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $fname $lname <$email>";

        echo 'section build done';

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            echo "Thank You! Your message has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        echo "There was a problem with your submission, please try again.";
    }

The URLS for this project are as follows: http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/

Register Pet: http://cvs.dev.dannycheeseman.me/base/contact-us/

Thank you for your time.

Daniel Cheeseman
  • 120
  • 1
  • 17
  • paste your html and javascript code on fiddle – Man Programmer Sep 02 '14 at 07:21
  • @ManProgrammer, Ok, I will try to add now. – Daniel Cheeseman Sep 02 '14 at 07:31
  • @pc-shooter - Did you read my question? If you have then you will see that it is not a duplicate. The example you have provided is a super simple form to ajax, not a dynamic form to ajax. – Daniel Cheeseman Sep 02 '14 at 07:32
  • @ManProgrammer: http://jsfiddle.net/zsxe44c8/ - Cheers. – Daniel Cheeseman Sep 02 '14 at 07:50
  • @DanielCheeseman please describe your problem? how could we help you – Man Programmer Sep 02 '14 at 07:58
  • @ManProgrammer - Ok. I have the code in the fiddle. I also have ajax/php code to send a form that I use on the contact form. The problem being, I need to send the 'Dynamic' register pet form via ajax and php. I can send the initial form (with no added pets) but when I add a pet by clicking on the add pet button I become unstuck. How do I send the extra pet fields to php via ajax? I am lost dude. – Daniel Cheeseman Sep 02 '14 at 08:16
  • 1
    Look into getting the `form` via jQuery and then use either `submit` or `serialize` http://api.jquery.com/serialize/ have a look at this to see how they prevent the default submit and then serialize the form http://stackoverflow.com/questions/1200266/submit-a-form-using-jquery – Rob Schmuecker Sep 02 '14 at 08:19
  • @RobSchmuecker, Hi, thanks for your answer. I already have a working ajax function and php handler that I use for the contact form. The problem being is that in the php, I have $fname = strip_tags(trim($_POST["fname"])); for the first name etc. So, if my add pet form was static, that would be fine. – Daniel Cheeseman Sep 02 '14 at 08:37
  • @RobSchmuecker BUT Clients might need to add a pet. They click on the add pet button and the pet-1 fieldset is cloned and given an id of #pet-2 via jquery. The ID of every input within that fieldset is also modified from *-1 to *-2. So. How do I pass that to php and send as an email? The php would have $petname1 = strip_tags(trim($_POST["pet-name-1"])); for the first fieldset but there is no $petname2 = strip_tags(trim($_POST["pet-name-2"])); as we are not sure if the user has added an extra pet or not.. – Daniel Cheeseman Sep 02 '14 at 08:38
  • @RobSchmuecker I do not want to declare this 50 times incaase the user adds 50 pets, I wish for it to be dynamic.. Not sure if I am making sense? – Daniel Cheeseman Sep 02 '14 at 08:38
  • 1
    @DanielCheeseman one way of doing this then would be to set a hidden value in the form of the number of pets and then loop based on that value in PHP. – Rob Schmuecker Sep 02 '14 at 08:41
  • @RobSchmuecker Thank you ever so much for your help! Really appreciate it.. :) – Daniel Cheeseman Sep 02 '14 at 08:43

1 Answers1

7

Seems like you want to post the whole form, including the input files generated dynamically.

if so, then you will want to see into using array of input.

<form method="POST" action="whereever.php>
    <input type="text" name="name[]" value="Dog" />
    <input type="text" name="name[]" value="Cat" />
    <input type="text" name="name[]" value="Snake" />
</form>

When the form is sent (whether by basic or AJAX), the PHP script can read the input as an array

<?php
echo $_POST['name'][0]."<br>";
echo $_POST['name'][1]."<br>";
echo $_POST['name'][2]."<br>";
?>

above script will output

Dog
Cat
Snake

This can be applied to all input. Does this help?

Addition

So in your case, you can do it like this:

<form>
<section>
Pet # 1
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>

<section>
Pet # 2
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>

<section>
Pet # 3
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
</form>

To read the POST dynamically

foreach($_POST["name"] as $key => $value)
{
    echo $value;

    /*or if you want to loop while accessing other fields too, you can do this*/

    echo "<br>".$_POST["name"][$key];
    echo "<br>".$_POST["lastname"][$key];

    /*this way you can access the other fields with the same <section> as well, just make sure you do not mess with the input placement*/
}
Hendyanto
  • 335
  • 1
  • 8
  • Wow.. Almost nailed it! Thank you! How would I now make this dynamic: "; ?> As I do not want to have to write this 50 times incase 50 pets were added. I am assuming there is some for each statement? – Daniel Cheeseman Sep 02 '14 at 08:36
  • 1
    I HAVE to thank you once more.. I was scratching my head and going round in circles for ages.. Your code works great. +100! – Daniel Cheeseman Sep 02 '14 at 09:16