Rails3 responding with js after json update
using http://blog.bernatfarrero.com/in-place-editing-with-javascript-jquery-and-rails-3/
The gem uses json to update, but how can I trigger my update.js.erb to update the different parts of my pages?
EDIT Using this in an invoice page. every item in the invoice has a price field that can be updated with best_in_place.
I need to update the Total Price for line item and amount due for invoice only after field has been updated successfully.
Ended up with something like:
respond_to do |format|
if @item.update_attributes(params[:item])
format.html { redirect_to order_url(@item.order_id), :notice => "Successfully updated item." }
format.js { }
format.json { head :ok }
Edited best_in_place.js line #175
loadSuccessCallback : function(data) {
this.element.html(data[this.objectName]);
// Binding back after being clicked
$(this.activator).bind('click', {editor: this}, this.clickHandler);
if(this.objectName == "item") $.getScript('update.js'); // If its an item, call update.js.erb
},
I wanted to do the exact same thing with best_in_place pcasa. In the current version (1.0.2), the loadSuccessCallback function triggers an ajax:success event. That allows you to do this in your application.js:
$('.best_in_place')
.best_in_place()
.bind('ajax:success', function(e) {
// do your post-json call magic
});
You don't need a view update.js.erb. As ezkl already pointed out, you need to set the respond_to of your controller to json. In addition, you need to activate best-in-place in your public/javascripts/application.js
$(document).ready(function() {
jQuery(".best_in_place").best_in_place()
});
and add it in your view:
<td><%= best_in_place task, :name, :type => :input, :nil => "Click to edit" %></td>
I have a tutorial on Ajax with Prototype and JQuery on my own site - and the JQuery Part uses best-in-place: http://www.communityguides.eu/articles/15
Have you tried something along the lines of:
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
format.json { head :ok }
format.js
else
format.html { render :action => "edit" }
format.json { render :json => @user.errors, :status => :unprocessable_entity }
end
end
end
I haven't tested this with the code in the tutorial, but the idea is that you have to tell the controller method to load the Javascript file. I'm not sure how this will interact with the redirect, but the principle is correct.
精彩评论