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).
-
$(document).ready(function() {
-
$('a.autosave').click(function() {
-
// get relative address of the current window/tab
-
var url = window.location.pathname;
-
// collect the data from the form with id "autosave-form"
-
$postData = $('form#autosave').serialize();
-
// submit the form
-
$.post(url, $postData, function(data) {
-
// after the ajax request is successful, redirect to the link target
-
window.location.href = $('#autosave').attr('href');
-
});
-
// prevent default behavior
-
return false;
-
});
-
});
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).
