Handling Ajax Forms in Colorbox

In my last post I talked about how to add links to other pages with Colorbox. This post is about how to handle Ajax forms with Colorbox. You may have noticed that when you submit a form from within Colorbox, it does a HTTP request rather than an Ajax request. This can be somewhat frustrating – especially if you are wanting to have your form submit via Ajax.

In this post we will cover the following:

  1. Create a small form with required fields.
  2. Create PHP processing to check the required fields.
  3. Open the form with Colorbox.
  4. Submit the form via Ajax and show the results in Colorbox.

Create a small form with required fields

First things first, let’s create our form. The form I am building has 4 fields. Here is the HTML for my form:

<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <table>
    <tr>
      <td><span>*</span><label for="company-name">Your Company Name:</label></td>
      <td><input type="text" name="company-name" id="company-name" value="<?php if(isset($_POST['company-name'])){echo $_POST['company-name'];} ?>" /></td>
    </tr>
    <tr>
      <td><span>*</span><label for="name">Your Name:</label></td>
      <td><input type="text" name="name" id="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>"/></td>
    </tr>
    <tr>
      <td><span>*</span><label for="email">Your Email:</label></td>
      <td><input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>"/></td>
    </tr>
    <tr>
      <td><label for="fax">Your Fax #:</label></td>
      <td><input type="text" name="fax" id="fax" value="<?php if(isset($_POST['fax'])){echo $_POST['fax'];} ?>"/></td>
    </tr>
  </table>
  <p>
    <input type="hidden" name="submit" />
    <input type="submit" name="submit" value="Submit" />
  </p>
</form>

Required fields are denoted by an asterisk. In my form I have three required fields and a fourth field for fax number. Now I’m going to check whether these required fields are filled in with a quick PHP script.

Create PHP processing to check the required fields

This PHP Script is meant to be easily update-able – so if I were to add more fields to my form I could easily check and save them. Insert this code just above your HTML code.

<?php
  if(isset($_POST['submit']))
  {
    //define required fields
    $required_fields = array(
      'company-name' => 'Your Company Name',
      'name' => 'Your Name',
      'email' => 'Your Email'
    );

    //define other fields
   $normal_fields = array(
     'fax' => 'Your Fax #'
   );

 //get any missing fields
 $missing_fields = array_diff_key($required_fields, $_POST);

 //only process if required fields exist
 if(empty($missing_fields))
 {
   //merge the required and normal arrays
   $defined_fields = array_merge($required_fields, $normal_fields);

   foreach($defined_fields as $key => $value)
   {
     //add to missing fields if the required value isn't filled - this is checked and displayed later
     if(array_key_exists($key, $required_fields) && empty($_POST[$key]))
     {
       $missing_fields[$key] = $required_fields[$key];
     }
     else
     {
       $defined_fields[$key] = $_POST[$key];
     }// if
   }// foreach
  //if there are missing fields or errors show them here.
  if(!empty($missing_fields))
  {
    echo '<p>Please fill in the following required fields.</p>';
    echo '<ul style="color: red;">';
    foreach($missing_fields as $key => $value)
    {
      printf('<li>%s</li>', $value);
    }// foreach
    echo '</ul>';
  }
  else
  {
    echo 'Ajax Form Submission via Colorbox Successful!';
  }// if

//display the form if necessary
if(!isset($_POST['submit']) || !empty($missing_fields)):
?>
<!--HTML FORM FROM ABOVE IN HERE-->
<?php endif; ?>

Open the form with Colorbox

Ok, now we’ve got our server side PHP script ready and our HTML form ready. It’s time to open this with Colorbox. I want this form to pop up in a Colorbox when the user clicks a link. Here is the HTML for my link:

<a href="myform.php" class="cbox-form">Fill out my Ajaxed Colorbox form!</a>

In order to open the form with Colorbox we need to add the following JavaScript to our page. This activates Colorbox on our form link.

jQuery(function(){
   jQuery('.cbox-form').colorbox({maxWidth: '75%'});
});

Great! Now our form is opening inside our Colorbox. If you click our Submit button now you will see that the page does a normal HTTP request and it refreshes. We want it to submit via Ajax – so here is what we do!

Submit the form via Ajax and show the results in Colorbox

Colorbox comes with an assortment of callback functions. These are described in detail on the Colorbox page. We are going to be making use of the onComplete callback.

Locate where you activated your Colorbox in the previous step. We will be modifying this to use the onComplete callback. Replace the previous code with this new code:

jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
  jQuery("#pre-process").submit(function(){
    jQuery.post(
      jQuery(this).attr('action'),
      jQuery(this).serialize(),
      function(data){
        jQuery().colorbox({html: data});
      }
    );
   return false;
 });
}});

If you test your form now you will see that it submits via Ajax now. If you fill all of your fields in you will see the “Ajax Form Submission via Colorbox Successful!” message. If you do not fill in some of the required fields then you sill see the Ajax display that you need to fill in some more fields.

Ah! Did you notice? The form submits via Ajax and shows the results – but if the required fields were not filled in, the next submission goes back to the old HTTP request method. Grrr! We will need to perform one more tweak in order to get it to work correctly.

We are going to create another function and use the onComplete callback once again. Replace the old JavaScript with the following final JavaScript:

jQuery(function(){
  jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
    cbox_submit();
  }});
});

//submit ajax form continually if needed
function cbox_submit()
{
  jQuery("#pre-process").submit(function(){
    jQuery.post(
      jQuery(this).attr('action'),
      jQuery(this).serialize(),
      function(data){
        jQuery().colorbox({html: data, onComplete: function(){
          cbox_submit();
        }});
      }
    );
    return false;
  });
}// cbox_submit

Alright! Now we have a fully functioning Ajax form that works inside Colorbox.

Recognize some of the code? That’s because George Truong wrote up a great tutorial on submitting forms via Ajax with Jquery.

Have a different way of doing this or a better solution? Let us and everyone else know by giving your two cents’ worth below.

This entry was posted in HTML, Javascript Code, jQuery, PHP Code and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.