Question

Is it possible to have multiple contact forms on one page and still validate and send an email without the page refreshing.

I have used the tutorial below but if copied obviously this still only validates the original form...

http://www.ajaxfreak.com/2009/12/03/submit-a-form-without-page-refresh-using-jquery/

I could copy the JS etc for each of the required forms but there must be a more efficient way of doing this, maybe with hidden values & form ids?.

Anybody have any ideas?

Thanks

Was it helpful?

Solution

It is certainly possible, unfortunately the demo manually builds the data string manually using IDs, which doesn't make it easy to convert to multiple forms. It would be much more convenient to use the .serialize() method on the form.

The following (simplified) example should work for any number of forms on the page that have the class "ajax". Input elements with the 'required' class will be checked for a value first, and will have background red color applied if it's missing:

$('form.ajax').submit(function() {
   var validates = true;
   $(this).find('input.required').each(function() {
      if($(this).val() == '') {
         $(this).css('background', '#ff9999');
         validates = false
      } else {
         $(this).css('background', '#ffffff');
      }
   }
   if(validates)  {
      $.ajax({
         type: "POST",
         url: "bin/process.php",
         $(this).serialize(),
         success: function() {
             // things to do on success here!
         }
      });
   }
   return false; // prevent normal form submission.
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top