How to AJAXify any POSTed web form

Probably not too practical in real life, but I wanted to see just how easy it could be to implement this. If you want a lazy way to automatically convert any normal HTML POST form (send email, submit information, etc.) into a quicker-looking AJAX form, here’s the quickest way to do it:

$('form[method=post]').on('submit',function(e) {
  e.preventDefault();
  var url = $(this).attr('action') || location.href;
  $(this).find(':button').prop('disabled',true);
  $.post(url, $(this).serialize(), function(data) {
    document.write(data);
  });
});

This doesn’t take into account things like errors or partial DOM manipulation. For that, you’ll probably want to customize the above code on a per-form basis.

Leave a Reply

Your email address will not be published. Required fields are marked *

*