I’m often building forms for client projects, and they nearly always prefer them have some AJAX goodness. To this end I’ve built a small jQuery file that gets added to all my projects. It depends on Malsup’s AjaxForm and Bassistance’s Form Validation.
/**
* Generic *SIMPLE* Ajax Form handling
*/
jQuery(document).ready(function($){
$('.simpleajaxform').each(function(){
$(this).attr('method', 'post');
var target = $(this).attr('target');
var func = $(this).attr('function');
options = {};
if( target || func ){
if( target ) $('#'+target).html('').hide();
options = {
success: simpleajaxform_success,
beforeSubmit: simpleajaxform_submit
};
}
$(this).ajaxForm(options);
});
});
/**
* On submit: clear any previous update and tell the user
* that we're trying to update
*/
function simpleajaxform_submit(formData, jqForm, options) {
if( !jqForm.valid() ) return false;
target = jqForm.attr('target');
if( target )
jQuery('#'+target).html('Updating, please wait...').removeClass('updated').addClass('updating').show();
return true;
}
/**
* Response: show message in target div.
*/
function simpleajaxform_success(responseText, statusText, xhr, jQForm){
if( jQForm === undefined )
jQForm = xhr;
if( jQForm === undefined ){
alert('Cannot handle response properly');
return;
}
target = jQForm.attr('target');
if( target )
jQuery('#'+target).removeClass('updating').addClass('updated').html(responseText);
hide = jQForm.attr('hide');
if( hide )
jQuery('#'+hide).hide();
handler = jQForm.attr('function');
if( handler )
eval( handler+'(responseText, jQForm)' );
}
Take any form that submits to an AJAX handler (see below for notes on WordPress and ‘action’), add the ‘simpleajaxform‘ class and either a ‘target‘ or ‘function‘ property. Job done.
Here’s a stripped down example using it:
<form class="simpleajaxform" action="<?php echo admin_url('admin-ajax.php');?>" target="targetdiv">
<input type="hidden" name="action" value="my_wp_action" />
<input class="required" type="text" name="message" value="" />
<input type="submit" name="submit" value="DO STUFF" />
</form>
WordPress, Javascript (jQuery) and ACTION
If you add a field named ‘action‘ in a form, then jQuery can get a bit confused by the syntax ‘jQuery(‘#someformid’).attr(‘action’,ajaxurl)‘. I’ll leave figuring that out as an exercise for the reader (or for a later post).
Download showcase plugin here:Â simple-ajax-form