Sep 29 / Richard Knop

JQuery autosave on click event

What does this simple jQuery snippet do? When you click on the link with class “autosave”, the form with id “autosave” is submitted via POST request to the same page. After that it redirects to the actual target of the link (href attribute).

  1. $(document).ready(function() {
  2.     $('a.autosave').click(function() {
  3.         // get relative address of the current window/tab
  4.         var url = window.location.pathname;
  5.         // collect the data from the form with id "autosave-form"
  6.         $postData = $('form#autosave').serialize();
  7.         // submit the form
  8.         $.post(url, $postData, function(data) {
  9.             // after the ajax request is successful, redirect to the link target
  10.             window.location.href = $('#autosave').attr('href');
  11.         });
  12.         // prevent default behavior
  13.         return false;
  14.     });
  15. });

This can be useful in numerous situations. For example, on the page where user can edit his/her profile, you want to have a link saying something like “view my profile”. But you don’t want less experienced users to click on the link and lose all changes they have made to their profile (which happens quite a lot).

Leave a Comment