My Rails app contains an Excel-like editable table, using best_in_place fields throughout. They work perfectly fine upon page load and I have no problem calling coffeescript functions on ajax:success
after a user edits a best_in_place field.
Since this is an Excel-like table, users can click a link to add a new placeholder row to the table. My create.js.erb file adds the row without a page reload. The new row has several table cells with best_in_place functionality, and updating them updates the database, so far so good.
The problem is that when a user then edits a best_in_place fields in one of the new rows, ajax:success
does not fire, therefore my coffeescript functions do not initiate.
I've confirmed the new table cells have the exact same class and data attributes as the existing table cells (ajax:success
is read on the class name).
Question- in this scenario, how do I initiate my coffeescript function if ajax:success
is not being recognized?
Milestone controller, both create and update actions
def create
@payment_schedule = PaymentSchedule.find(params[:id])
build_default_milestone # this builds a placeholder milestone
if @milestone.save
increment_milestone_positions # this relates to a sortable table
respond_to do |format|
format.js
format.html { redirect_to :back }
end
else
respond_to do |format|
format.js
format.html { redirect_to :back }
end
end
end
def update
@milestone = Milestone.find(params[:id])
respond_to do |format|
if @milestone.update(milestone_params)
update_milestone_amounts
format.html { redirect_to(:back) }
format.json { respond_with_bip(@milestone) }
else
format.html { redirect_to(:back) }
format.json { respond_with_bip(:back) }
end
end
end
Create.js.erb
$('#milestone-body').prepend('<%= escape_javascript(render partial: 'row_add', locals: { milestone: @milestone }) %>');
Coffeescript function
update-percent
is the class name of the best_in_place field in question. This function fires perfectly for the existing rows, just not the new ones.
$('.update-percent').on 'ajax:success', (event, data, status, xhr) ->
...
Any suggestions on how to solve this?
The issue is resolved. The problem was not that ajax:success wasn't firing, it's that (for reasons still unknown) I had to read ajax:success at the table body level instead of the table cell in question. Apparently this is a somewhat common issue, where when adding new elements to the DOM after it's originally loaded, you need to read ajax:success higher up the DOM.
Thank you to those who provided input.