10 Apr

CMS Design with jQuery and PHP: moving a recaptcha form

reCAPTCHA is a free captcha service which lets you use their captchas for your programs.

I wanted to create a login/password-reminder page, with recaptcha used in both forms.

Unfortunately, you can’t have two recaptcha images on the same page, as every time the image is displayed, it is a new image and the old one is no longer valid (which means that if it’s used in two forms, you can only ever submit the second one.)

A solution that came to me is to “move” the captcha from one form to the other, so you’re only ever actually using one recaptcha.

So how is it done?

demo

In the demo, I’m using jQuery UI to separate the forms into two tabs.

If you look at the source, you will see there is one recaptcha object, in the first table. The table row has the ID “captcha”.

The entire JavaScript used in the demo is this:

$(function(){
	// remove the captcha's script element
	$('#captcha script').remove();
	// set up tabs
	$('.tabs').tabs({
		show:function(event,ui){
			// if the captcha is already here, return
			if($('#captcha',ui.panel).length)return;
			// move the captcha into this panel
			$('table tr:last',ui.panel).before($('#captcha'));
		}
	});
});

The first thing that’s done is that the captcha’s <script> element is removed. If you don’t remove it, then when the table row is moved, the script will be re-interpreted, causing breakage.

Now, the tabs are initialised. We set the show event to run a little function. That function checks to see if the captcha row is contained in the newly-shown panel. If it’s not, then it’s moved there using this line:

$('table tr:last',ui.panel).before($('#captcha'));

The above line means “insert/move the #captcha element in front of the last tr in the table contained in ui.panel“.

This is part of the User Management And Access Control chapter of the up-coming book “CMS Design using jQuery and PHP” ( a sequel, sort-of, to my jQuery 1.3 with PHP).