JQuery tricks: using Greybox + form plugin for a modal dialog box

I was looking for a replacement for the Yahoo UI library's dialog widget (here's the demo I was studying). Specifically, I wanted something where I could write a simple CGI with form and error checking, and put that in a dialog box I could call from different pages in my application. Preferably something that could be added with unobtrusive javascript to an existing view.

Back in the day of Internet Explorer 3 and Netscape 4, you would just use window.open() for this. But for some reason, the kids today are all excited about AJAX, DHTMLish gizmos; just looking at the plugins available for the cool JQuery library, you've got Thickbox and Tweenbox and Slightly Thickerbox and Greybox Redux. None of them seems to do exactly what I want, which is to create a dialog box that the user can interact with normally until he's done with it, with a CGI that can report errors and present its form again and again as many times as needed to complete the transaction; and where, once done, the dialog will close by itself, maybe triggering some neat page update based on the newly entered data.

The cool form plugin provided a great deal of help, but I got into a bit of a muddle about how the CGI can let the javascript know it's done. I wrote this page as a simple demo to help me figure it out. You can see it in action by clicking the link below:

Demo: Change password

How it works

Create a greybox (calling $.GB_show()). The greybox has an iframe inside, which isn't much use. Remove that and replace it with a plain old DIV. Use the JQuery load() method to load the CGI form into that DIV. Use the form plugin's ajaxForm method to change the loaded CGI form's behaviour, so that instead of a regular submit, it gets submitted via AJAX and loaded back into the greybox. Praise to all those callback hooks provided by load() and ajaxForm().

NOW, the problem is making sure that until a certain condition is met (i.e, the CGI script is "done"), it will keep reloading itself into the dialog box (the div); ajaxForm's after callback lets you do it once, but I was confused how to keep reseting it. This morning in the car park I finally unknotted my thinking: if the CGI isn't done, grab its output (all the HTML) and reload it into the dialog box, calling ajaxForm on it again.

This is just a proof-of-concept, not an actual plugin or even a proper generic function. All the code is either in this page or in the unmodified jquery.js,greybox.js and form.js files included (all files are from the JQuery subversion repository). The source of the demo.php CGI is here: demo.php.

Dotan Dimet. You can comment on the blog entry here.