$.fn.hijackChangeItemPlacement = function() {
var confirm_box = $('<div class="inline notice message" style="display: none;"></div>');
var loading = $('<p>Väntar på svar…</p>');
var confirm_box_class = '', confirm_box_msg = '';
$(this).append(confirm_box);
$(this).submit(function() {
if ( $(confirm_box).css('display') == 'block' ) {
$(confirm_box).slideUp('500', function() {
setTimeout(function() { $(confirm_box).removeClass('important information').addClass('notice').empty().append(loading).slideDown(); }, 200);
});
} else {
$(confirm_box).empty().append(loading).slideDown();
}
$.ajax({
beforeSend: function(request) { request.setRequestHeader('Accept', 'text/javascript'); },
data: $(this).serialize(),
type: 'PUT',
success: function(response) {
confirm_box_class = 'information';
confirm_box_msg = '<p>' + response + '</p>';
setTimeout(function() { $(confirm_box).slideUp(); }, 3000);
},
error: function(request) {
confirm_box_class = 'important';
confirm_box_msg = '<p>'+request.responseText+'</p>' + '<input type="hidden" name="new_placement_confirmed" value="1">' + '<input type="submit" value="Fortsätt flytten">';
},
complete: function() {
$(loading).replaceWith(confirm_box_msg);
$(confirm_box).addClass(confirm_box_class, 500);
}
});
return false;
});
}
$('.edit_item').hijackChangeItemPlacement();
Refactorings
No refactoring yet !
So this is just something I wrote for talking with the server-side and getting either a success or failure and then doing some animations related to viewing the response message, etc. I'm just curious to how you could do this in a cleaner and more optimized way.