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:

01 <form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
02   <table>
03     <tr>
04       <td><span>*</span><label for="company-name">Your Company Name:</label></td>
05       <td><input type="text" name="company-name" id="company-name" value="<?php if(isset($_POST['company-name'])){echo $_POST['company-name'];} ?>" /></td>
06     </tr>
07     <tr>
08       <td><span>*</span><label for="name">Your Name:</label></td>
09       <td><input type="text" name="name" id="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>"/></td>
10     </tr>
11     <tr>
12       <td><span>*</span><label for="email">Your Email:</label></td>
13       <td><input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>"/></td>
14     </tr>
15     <tr>
16       <td><label for="fax">Your Fax #:</label></td>
17       <td><input type="text" name="fax" id="fax" value="<?php if(isset($_POST['fax'])){echo $_POST['fax'];} ?>"/></td>
18     </tr>
19   </table>
20   <p>
21     <input type="hidden" name="submit" />
22     <input type="submit" name="submit" value="Submit" />
23   </p>
24 </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.

01 <?php
02   if(isset($_POST['submit']))
03   {
04     //define required fields
05     $required_fields = array(
06       'company-name' => 'Your Company Name',
07       'name' => 'Your Name',
08       'email' => 'Your Email'
09     );
10
11     //define other fields
12    $normal_fields = array(
13      'fax' => 'Your Fax #'
14    );
15
16  //get any missing fields
17  $missing_fields = array_diff_key($required_fields, $_POST);
18
19  //only process if required fields exist
20  if(empty($missing_fields))
21  {
22    //merge the required and normal arrays
23    $defined_fields = array_merge($required_fields, $normal_fields);
24
25    foreach($defined_fields as $key => $value)
26    {
27      //add to missing fields if the required value isn't filled - this is checked and displayed later
28      if(array_key_exists($key, $required_fields) && empty($_POST[$key]))
29      {
30        $missing_fields[$key] = $required_fields[$key];
31      }
32      else
33      {
34        $defined_fields[$key] = $_POST[$key];
35      }// if
36    }// foreach
37   //if there are missing fields or errors show them here.
38   if(!empty($missing_fields))
39   {
40     echo '<p>Please fill in the following required fields.</p>';
41     echo '<ul style="color: red;">';
42     foreach($missing_fields as $key => $value)
43     {
44       printf('<li>%s</li>', $value);
45     }// foreach
46     echo '</ul>';
47   }
48   else
49   {
50     echo 'Ajax Form Submission via Colorbox Successful!';
51   }// if
52
53 //display the form if necessary
54 if(!isset($_POST['submit']) || !empty($missing_fields)):
55 ?>
56 <!--HTML FORM FROM ABOVE IN HERE-->
57 <?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:

1 <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.

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

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:

01 jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
02   jQuery("#pre-process").submit(function(){
03     jQuery.post(
04       jQuery(this).attr('action'),
05       jQuery(this).serialize(),
06       function(data){
07         jQuery().colorbox({html: data});
08       }
09     );
10    return false;
11  });
12 }});

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:

01 jQuery(function(){
02   jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
03     cbox_submit();
04   }});
05 });
06
07 //submit ajax form continually if needed
08 function cbox_submit()
09 {
10   jQuery("#pre-process").submit(function(){
11     jQuery.post(
12       jQuery(this).attr('action'),
13       jQuery(this).serialize(),
14       function(data){
15         jQuery().colorbox({html: data, onComplete: function(){
16           cbox_submit();
17         }});
18       }
19     );
20     return false;
21   });
22 }// cbox_submit

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

Advertisements
By Rz Rasel Posted in jQuery

3 comments on “Handling Ajax Forms in Colorbox

  1. I follow your code, but pop-up Colorbox not showing form, @ start up my page sho form. I am implementing all above code in single php page.
    I want to ask you another question how I implement this functionality with two pages:Colorbox form in one page and form processing in another page.

  2. Hi, I follow your code. when i submit form it works fine but it doesn’t change my color box content….pls suggest… Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s