title: Sending a dynamic form via jquery ajax php
body: <p>I have a pet registration form where people can add a new pet.</p>
  
  <p>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.</p>
  
  <p>After fruitless web searching, I now need to know how to send this via php and ajax.</p>
  
  <p>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.</p>
  
  <p>Here is the fiddle: <a href="http://jsfiddle.net/zsxe44c8/" rel="nofollow">http://jsfiddle.net/zsxe44c8/</a></p>
  
  <p>Here is the code for the add pet form:</p>
  
  <pre><code>&lt;form id="register-pet-form" data-quantity="1"&gt;
  
              &lt;fieldset id="practiceField" class="row"&gt;
  
                  &lt;div class="col-md-6 push-md-6"&gt;
  
                      &lt;h3&gt;Practice&lt;/h3&gt;
  
                      &lt;select name="practice"&gt;
                          &lt;option value=""&gt;Value 1&lt;/option&gt;
                          &lt;option value=""&gt;Value 2&lt;/option&gt;                    
                      &lt;/select&gt;
  
                  &lt;/div&gt;
  
              &lt;/fieldset&gt;
              &lt;!--/#practiceField--&gt;
  
              &lt;fieldset id="ownerDetails" class="row"&gt;
  
                  &lt;div class="col-md-6"&gt;
  
                      &lt;h3&gt;Your details&lt;/h3&gt;
                      &lt;select name="title"&gt;
                          &lt;option value="Mr"&gt;Mr&lt;/option&gt;
                          &lt;option value="Mrs"&gt;Mrs&lt;/option&gt;
                          &lt;option value="Miss"&gt;Miss&lt;/option&gt;
                          &lt;option value="Ms"&gt;Ms&lt;/option&gt;
                          &lt;option value="Dr"&gt;Dr&lt;/option&gt;
                          &lt;option value="Prof"&gt;Prof&lt;/option&gt;
                      &lt;/select&gt;
  
                      &lt;input name="fname" type="text" placeholder="First Name"&gt;
  
                      &lt;input name="lname" type="text" placeholder="Last Name"&gt;
  
                      &lt;input name="number" type="text" placeholder="Contact Number"&gt;
  
                      &lt;input name="email" type="text" placeholder="Email Address"&gt;
  
                  &lt;/div&gt;
  
                  &lt;div class="col-md-6"&gt;
  
                      &lt;h3&gt;Your Address&lt;/h3&gt;
  
                      &lt;input name="address1" type="text" placeholder="Address 1"&gt;
  
                      &lt;input name="address2" type="text" placeholder="Address 2"&gt;
  
                      &lt;input name="address3" type="text" placeholder="Address 3"&gt;
  
                      &lt;input name="postcode" type="text" placeholder="Postcode"&gt;
  
                  &lt;/div&gt;
  
              &lt;/fieldset&gt;
              &lt;!--/#ownerDetails--&gt;
  
              &lt;fieldset id="pet-1" class="row"&gt;
  
                  &lt;div class="col-md-12"&gt;
  
                      &lt;h3&gt;Pet Details&lt;/h3&gt;
  
                  &lt;/div&gt;
  
                  &lt;div class="col-md-6"&gt;
  
                      &lt;input name="pet-name" type="text" placeholder="Pet Name"&gt;
  
                      &lt;input name="pet-breed" type="text" placeholder="Pet Breed"&gt;
  
                      &lt;input name="pet-age" type="text" placeholder="Age of pet"&gt;
  
                  &lt;/div&gt;
  
                  &lt;div class="col-md-6"&gt;
  
                      &lt;select name="petGender"&gt;
                          &lt;option value="Female"&gt;Female&lt;/option&gt;
                          &lt;option value="Male"&gt;Male&lt;/option&gt;
                      &lt;/select&gt;
  
                      &lt;select name="petType"&gt;
                          &lt;option value="Dog"&gt;Dog&lt;/option&gt;
                          &lt;option value="Cat"&gt;Cat&lt;/option&gt;
                          &lt;option value="Rabbit"&gt;Rabbit&lt;/option&gt;
                          &lt;option value="Gerbil"&gt;Gerbil&lt;/option&gt;
                          &lt;option value="Guinea Pig"&gt;Guinea Pig&lt;/option&gt;
                          &lt;option value="Hamster"&gt;Hamster&lt;/option&gt;
                          &lt;option value="Mouse"&gt;Mouse&lt;/option&gt;
                          &lt;option value="Rat"&gt;Rat&lt;/option&gt;
                          &lt;option value="Chinchilla"&gt;Chinchilla&lt;/option&gt;
                          &lt;option value="Other"&gt;Other&lt;/option&gt;
                      &lt;/select&gt;
  
                  &lt;/div&gt;
  
                  &lt;div class="col-md-12"&gt;
  
  
                      &lt;input name="pet-desc" type="text" placeholder="Pet Description"&gt;
  
                      &lt;textarea name="additional-comments" placeholder="Additional Comments"&gt;&lt;/textarea&gt;
  
  
                  &lt;/div&gt;
  
              &lt;/fieldset&gt;
              &lt;!--#petDetails--&gt;
  
              &lt;div id="form-tools" class="row"&gt;
  
                  &lt;div class="col-md-6"&gt;
  
                      &lt;a class="add-pet" href="#"&gt;Add another pet&lt;/a&gt;
  
                  &lt;/div&gt;
  
                  &lt;div class="col-md-6 right"&gt;
  
                      &lt;input type="submit" value="Submit"&gt;
  
                  &lt;/div&gt;
  
              &lt;/div&gt;
              &lt;!--/#form-tools--&gt;
  
          &lt;/form&gt;
  </code></pre>
  
  <p>Here is the jQuery code for the add pet form:</p>
  
  <pre><code>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('&lt;a data-id="' + newVal + '" class="js-remove-pet remove-pet" href="#"&gt;Remove this pet&lt;/a&gt;');
  
          $('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('&lt;a href="" class="form-button-2" id="js-add-pet"&gt;Add another pet&lt;/a&gt;');
  
              $('.add-pet').on('click',function() {
  
                  var count = $('.ispet').length + 1;
  
                  $('.ispet').last().after('&lt;fieldset id="pet-'+ count +'" class="ispet"&gt;' + newBlock + '&lt;/fieldset&gt;');
  
                  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;
      });
  }
  </code></pre>
  
  <p>Now here is the code for the ajax contact form that is working and I wish to modify for the add pet form:</p>
  
  <pre><code>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(
                  '&lt;div class="alert alert-success" role="alert"&gt;&lt;i class="fa fa-check"&gt;&lt;/i&gt; &lt;strong&gt;Your message has been sent successfully&lt;/strong&gt;&lt;/div&gt;'
              ).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');
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>&lt;?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 &lt;$email&gt;";
  
          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.";
      }
  </code></pre>
  
  <p>The URLS for this project are as follows: <a href="http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/" rel="nofollow">http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/</a></p>
  
  <p>Register Pet: <a href="http://cvs.dev.dannycheeseman.me/base/contact-us/" rel="nofollow">http://cvs.dev.dannycheeseman.me/base/contact-us/</a></p>
  
  <p>Thank you for your time.</p>