Rails - Why jQuery doesn't load after submitting my form remotely

For simplicity, I have a form that updates a partial one. Nothing special. In partial, I have a jQuery sortable list. Before updating the form, I can easily drag and drop things in the list.

However, after updating the list, it, like js, does not restart, and I need to refresh the entire page in order to get started again.

I tried everything, even borrowed a jQuery demo application from Ryan Bates Esq. here. This does not work even after I added js shizzle to partial.

I am sure it is simple, but I am new to ajax / jQuery and really afraid.

View:

#test_one = render "test_one" 

partial "test_one"

 = form_for @location, :remote => true do |f| %table %tr= collection_select(:location, :type_ids, Type.all, :id, :name, {:prompt => true}, :multiple => true, :class=>"chzn-select") %tr %td %ul#types.unstyled{"data-update-url" => sort_types_locations_url} - @types.each do |type| = content_tag_for :li, type do %span.handle [Drag] = type.name 

update.js.erb

 $("#test_one").html('<%= escape_javascript render("test_two") %>'); 

And in my controller:

  def update @location = Location.find(params[:id]) @types = @location.types.order('location_types.position').limit(2) respond_to do |format| if @location.update_attributes!(params[:location]) flash[:notice] = 'Settings updated successfully' format.html { redirect_to edit_location_path } format.js else format.html { render action: "edit_access" } format.js { render action: "update_access_errors" } end end end 

And finally in locations.js.coffee

 jQuery -> $('#types').sortable( axis: 'y' update: -> $.post($(this).data('update-url'), $(this).sortable('serialize')) ) 

The update works, I get no errors, and I have nothing in my console. I have lost a lot with this now - how can I get js to reboot after I update the record?

+4
source share
1 answer

The reason is because your custom js (about sorting) are loaded into the finished document and will not be resumed after a partial update.

Solution: wrap your custom js in a function. Call this function when the document is ready and updating occurs.

 # locations.js.coffee $ -> $(document).custom_js() $.fn.custom_js -> $('#types').sortable( axis: 'y' update: -> $.post($(this).data('update-url'), $(this).sortable('serialize')) ) # update.js.erb $("#test_one").html('<%= escape_javascript render("test_two") %>'); $(document).custom_js(); 

Side note about js user function: there is no need to wrap all user codes here, only the part related to what Ajax will be added / updated.

+5
source

Source: https://habr.com/ru/post/1481958/


All Articles