<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

jQuery AJAX-Enabled Forms in Modal Dialog

Published on
69,363 Points
57,763 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
Comment
Author:anoyes
14 Comments
LVL 16

Expert Comment

by:CodedK
This is a nice article to have in hand. (I will probably print this)
Thank you for sharing :)
0

Expert Comment

by:ajayubbott
How about Editing a record from a list of several records in the base page in the modal dialog?
Is it possible,
0
LVL 16

Author Comment

by:anoyes
Ajayubbott,

Absolutely possible.  It should work without much modification to what's detailed in this article, because all this is showing how to do is to load up some link in a modal dialog, so if you can link to your edit page, you should be able to use this same procedure.
0
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

LVL 16

Expert Comment

by:CodedK
0

Expert Comment

by:rajneesh1978
Please help to let me know how to modify the script for calling ASP page
0
LVL 16

Author Comment

by:anoyes
Rajneesh1978, are you looking to post to an ASP page as opposed to a PHP page?  As long as the "action" attribute of the form is set to point to your ASP page, then that's where the AJAX request will go to.

Then, to detect the AJAX and respond accordingly, it'd look something like this (you'll have to excuse me, my ASP's a little rusty):

' Check the X-Requested-With header to see if this is an AJAX request
dim isAJAX
var isAJAX = Iif(Request.ServerVariables('HTTP_X_REQUESTED_WITH') = 'XMLHttpRequest', true, false)

' We've got access to our POST variables as usual
Dim task
task = Request('task')

' manipulate, save to database, whatever

if (isAJAX) {
  Response.Write("alert('the task " + task + " was saved!');")
} else {
  Response.Redirect('saved.html')
}

Open in new window

0
LVL 16

Author Comment

by:anoyes
Oops, bad format on that If / Else

If isAJAX Then
  Response.Write("alert('the task " + task + " was saved!');")
Else
  Response.Redirect('saved.html')
End If

Open in new window

0
 

Administrative Comment

by:Mark Wills
Hi rajneesh1978,

That almost sounds like the basis for a question.

If you are still having problems, can I suggest you raise a question, reference this Article, and post a comment here so anoyes (and / or other experts) can attend to your problem specifically ?

Cheers,
Mark Wills
0
LVL 1

Expert Comment

by:admod
Hi Author, Good work , I vote you with full mind, Friend I need same like thick box structure
for file upload. Please Give me any resource

Thankfully
Anes
0
 

Administrative Comment

by:tigermatt
Email address posted above has been removed. We would prefer all discussion to be kept on the site, for the benefit of future readers

tigermatt
EE Page Editor
0

Expert Comment

by:kuubz
I'm trying to make the above work with the bassistance  validate plugin. Is there any documentation available about this?

Best,

Mike
0
LVL 3

Expert Comment

by:teodor birca
Not work in Chrome
0
LVL 75

Expert Comment

by:Michel Plungjan
I suggest you change click to .on("click",function(e) { e.preventDefault();
instead of the return false you have now
0
LVL 36

Expert Comment

by:Loganathan Natarajan
Nice.
0

Featured Post

Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Join & Write a Comment

The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month