Skip to content

Instantly share code, notes, and snippets.

@zilkey
Created March 23, 2010 18:28
Show Gist options
  • Save zilkey/341494 to your computer and use it in GitHub Desktop.
Save zilkey/341494 to your computer and use it in GitHub Desktop.
(function($) {
$.extend($, {
updateContent : function updateContent(event, newContent) {
var $contentKeyElements = $(newContent).filter('[data-content-key]');
$contentKeyElements.each(function() {
var contentKey = $(this).attr("data-content-key");
$("[data-content-key=" + contentKey + "]").html($(this).html());
});
$(document).trigger('content-updated');
}
});
$(function() {
$("form[data-remote-content=true]").live("submit", form);
$("a[data-remote-content=true]").live("click", link);
});
function form(event) {
var form = $(event.target).closest("form");
var options = {
type : form.attr('method') || "GET",
url : form.attr('action'),
data : form.serialize()
};
$.ajax({
type : options.type,
url : options.url,
data : options.data,
dataType : 'html',
global : false,
success : function success(response, status) {
$.updateContent(event, response);
}
});
return false;
}
function link(event) {
var link = $(event.target).closest("a");
var type = (link.attr('data-method') || "GET").toUpperCase();
var options = {
url : link.attr('href'),
type : type
};
if (type === 'PUT') {
options.type = 'POST';
options.data = {"_method" : "put"}
} else if (type === 'DELETE') {
options.type = 'POST';
options.data = {"_method" : "delete"}
}
var should_run = true;
var message = link.attr("data-confirm");
if (message) {
should_run = confirm(message);
}
if (should_run) {
$.ajax({
type : options.type,
url : options.url,
data : options.data,
dataType : 'html',
global : false,
success : function success(response, status) {
$.updateContent(event, response);
}
});
}
return false;
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment