<

jQuery AJAX-Enabled Forms in Modal Dialog

Published on
70,192 Points
58,592 Views
16 Endorsements
Last Modified:
Awarded
Community Pick
It's a problem I'm sure many of you have faced in developing web applications.  You've got a form to add a new something - perhaps a customer or an item in a to-do list.  When the user clicks that link to add a new item, a new page loads, they fill in the data, hit save, and then get re-directed back to the original page.  Wouldn't it be easier if they clicked that link and the form opened in a modal dialog instead, allowing them to quickly enter their information and hit save without ever having to move from page to page?  Now many of you are probably saying "Yah, that's easy, just create a div on your page, put the form in there, and make that your dialog."  Well that's great, but what if you're trying to achieve maximum compatibility? What happens if for whatever reason a user has JavaScript disabled in their browser?  Suddenly that entire 'add' functionality is lost.

What we'll look at in this article is how to create a generic function that will dynamically build a dialog, load the page via AJAX and display only the form, and then submit that form via AJAX, all without having to make a single change to your form.
For this article, I will be using the core jQuery library (available at http://jquery.com/) as well as the jQuery UI library (http://jqueryui.com/).  At the very least, you will need the UI core and the Dialog widget. The current versions as of writing this article are 1.3.2 of the jQuery library, and 1.7.2 of the jQuery UI library - those are the versions I will be using here.  While these same steps will probably work with older versions of the library, I can't make any guarantees.

1. Add the libraries to your page


Let's start by grabbing a copy of the jQuery libraries and adding them to our page.  If you prefer not to store them locally, you can use the copy hosted by Google Code - this also ensures you have the latest release of the libraries.  You can get the links at http://code.google.com/apis/ajaxlibs/documentation/index.html#jquery.  Just be sure to update the paths in the script tags below.  I'll assume though that you're hosting them locally, in the 'js' folder at the root of your site.
<script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui-1.7.2.custom.min.js"></script>

Open in new window

Your jQuery UI download should have also included a base theme for the library.  It'd be under the css directory in the zip file.  Let's go ahead and move that into our site too, and add import the stylesheet onto the page.

NOTE: If you're using jQuery UI from Google Code, the themes are available there, too.  For a complete list of all the jQuery code hosted by Google Code, take a look at http://blog.jqueryui.com/2009/03/jquery-ui-171/.
<link type="text/css" href="/css/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />

Open in new window

I'm also going to create one last JS file, I'll call it ajax-dialog-forms.js, in my js folder, and include that on my page.
<script type="text/javascript" src="/js/ajax-dialog-forms.js"></script> 

Open in new window

2. Set up the form


This process should work with just about any form with minimal, if any, changes.  For this example I'm just going to create a form that POSTs to "saveData.php", and just adds a task to a to-do list. For this example I've created a new HTML page to hold the form, called "new.html".
<div>
  <form action="saveData.php" method="post">
   <p>Task: <input type="text" name="task" /></p>
   <p><input type="submit" name="submit" value="Add Task" /></p>
  </form>
</div>

Open in new window

Simple form - just has one input and a submit button.  For the purpose of this tutorial I'm not going to go through the whole process of actually saving this to the database, etc.; I'll assume that you can do that on your own or find other examples on how to do so - it's outside the scope of this article.  But, before continuing, you should make sure that this form works properly.

3. The JavaScript


OK, let's open up that file we created earlier in our js folder, ajax-dialog-forms.js.  This is where we'll put all the code to turn normal forms into popup dialogs.  Here's the full code, and then I'll go through it bit by bit and explain everything.
 $(document).ready(dialogForms);

function dialogForms() {
  $('a.dialog-form').click(function() {
    var a = $(this);
    $.get(a.attr('href'),function(resp){
      var dialog = $('<div>').attr('id','formDialog').html(resp);
      $('body').append(dialog);
      dialog.find(':submit').hide();
      dialog.dialog({
        title: a.attr('title') ? a.attr('title') : '',
        modal: true,
        buttons: {
          'Save': function() {submitFormWithAjax($(this).find('form'));},
          'Cancel': function() {$(this).dialog('close');}
        },
        close: function() {$(this).remove();},
        width: 'auto'
      });
    }, 'html');
    return false;
  });
}

function submitFormWithAjax(form) {
  form = $(form);
  $.ajax({
    url: form.attr('action'),
    data: form.serialize(),
    type: (form.attr('method')),
    dataType: 'script'
  });
  return false;
} 

Open in new window

OK, so, little by little.
 $(document).ready(dialogForms);

Open in new window

This line is responsible for telling the browser that when the DOM is ready, we want to run the dialogForms function (see http://docs.jquery.com/Events/ready).

Now the dialogForms function is where we do our heavy lifting.  On the first line of this function, we want to target all the anchor (<a>) elements that have the class dialog-form, and attach a click function to them.
 $('a.dialog-form').click(function() {

Open in new window

Next, we will execute an AJAX GET request using jQuery's built-in $.get function.  We will request the url specified by the link's href attribute, and when the request completes we will execute a function and pass it the response (which is the HTML of the page).

After we have the HTML of the page we've requested, we can use jQuery to build a div on the page that will function as the target of our call to .dialog, and set the HTML of that dialog to be the form that is contained on that remote page.  When this is done we append the new div to the page, and call the jQuery UI .dialog function on it to create the modal popup.

4. Submitting the form


The new dialog we've created has two buttons - OK and Cancel.  The cancel button closes the dialog and then removes it from the page.  Clicking the save button calls a second function, submitFormWithAjax, which not surprisingly submits the specified form using AJAX.

Unfortunately this is about the point where I can no longer give exact instructions, because how exactly to handle this AJAX form submission depends on your application.  Regardless of the language you're using, however, it's likely that you will need to make some changes to the script that handles the submission (saveData.php in this example) to detect that the form was submitted via AJAX and respond accordingly.

For example, let's say that normally my PHP code would execute header("Location: successful.php"); when the form was successfully saved.  This will not work with this AJAX request since the request with JS is all being handled client-side and we're trying to use some server-side code.

Exactly how to detect this AJAX request, again, depends on your language and/or framework that you might be using.  For example, in the Zend Framework, you can use
$this->_request->isXmlHttpRequest()

Open in new window

to detect if it's an AJAX request. Luckily, however, jQuery automatically sets the X-Requested-With header when it makes a request, so you always have a fall back. I'll check this header in my PHP script to see how to handle the response:
<?php
// Check the X-Requested-With header to see if this is an AJAX request
$isAJAX = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ? true : false;

// We've got access to our $_POST variables as usual
$task = $_POST['task'];

// manipulate, save to database, whatever

if ($isAJAX) {
  echo "alert('the task '" . $task . "' was saved!');";
} else {
  header("Location:saved.html");
}

Open in new window


By checking the X-Requested-With header value, we can see if this request has been made with AJAX or via a regular post.  You'll note that the only point where the type of the request matters is when it comes time to sending a response back to the browser.  With an AJAX request, we need to return something that the client-side browser can understand and execute, and in this case we're using a simple javascript alert.  If it's not an AJAX request, then we'll execute a typical PHP redirect and send the user to 'saved.html'.

So there you have an intro to viewing forms as a dialog and then submitting the form using AJAX with jQuery.

And here are the files I used:
jquery-form-dialog.zip
16
Author:anoyes
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free