Skip to content

Instantly share code, notes, and snippets.

@mbbx6spp
Created April 10, 2010 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbbx6spp/362082 to your computer and use it in GitHub Desktop.
Save mbbx6spp/362082 to your computer and use it in GitHub Desktop.
UJS translation of ugly RJS problem posted to Devchix that I responded to on 2010-04-10.
# PUT /users/1
def update
@user = @session_user
respond_to do |format|
if @user.update_attributes(params[:user])
format.js do
render :json => {:status => 'success', :html => (render_to_string(:partial => 'display_avatar', :locals => { :user => @user })) }
end
format.html do
flash[:notice] = 'The resource was updated'
redirect_to your_resources_url
end
else
format.js do
render :json => {:status => 'error', :html => (render_to_string(:partial => 'avatar_errors', :locals => { :user => @user })) }
end
format.html do
flash[:notice] = 'There were errors in the form'
render :action => 'edit'
end
end
end
end
# replacing original code of:
# render :update do |page|
# if @user.update_attributes(params[:user])
# page.hide "upload-avatar"
# page.replace_html "avatar-error", ""
# page.replace "avatar", :partial => "display_avatar", :locals => {:user => @user}
# else
# page.insert_html :before, "disclaimer", :partial => "avatar_errors", :locals => {:user => @user}
# end
# end
(function ($) {
$(document).ready(function () {
// you can just use $('selector_for_editor_form').submit(...) instead if the form isn't
// dynamically added to the DOM and available to bind events to on page ready event.
// This can also be turned very easily into a jQuery plugin so you would only need to do:
// $('selector_for_edit_form').ajaxSubmit() or something like that.
$('selector_for_edit_form').live('submit', function(e) {
var serializedData = $(this).serialize();
var actionUrl = $(this).attr('action');
$.getJSON(actionUrl, serializedData, MY_APP.users.editResponse)
return false;
});
});
// Assumes your application has a namespace that you can add your own code to called MY_APP.users:
MY_APP.users.handleEditResponse = function (data, statusText) {
var status = data['status'];
var html = data['html'];
if ('success' === status) {
$('#upload-avatar').hide();
$('#avatar-error').html('');
$('#avatar').html(html);
} else {
// perhaps this is what you really want?
$('#avatar-error').html(html);
// if not then take the above line out and just use:
$('#disclaimer').before(html);
}
};
}) (jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment