Question

I am attempting to use ajax to load a form into my page which is partly working. The issue i seem to be having is that when the link is clicked the content loads, but the the links disappears, also when the content is loaded, none of the javascript within that content area works

Sidebar with links

- content_for :sidenav do
  - @pages.each do |obj|
    %li= link_to(obj.name, edit_admin_page_path(obj), :remote => true)

Ajax to render partial

$('#page_view').html('<%= escape_javascript (render :partial => 'edit') %>')

Partial to be render

= simple_form_for(@page, :url => admin_page_path(@page), :method => :put, :html => { :class => 'form-vertical' }) do |form|
  = render form
Était-ce utile?

La solution

Content

You mention your links / content will disappear after the Ajax update

The problem will be to do with this line:

$('#page_view').html('<%= escape_javascript (render :partial => 'edit') %>')

Your links will fall within the #page_view element, meaning when you update its HTML, you remove the links / other content too. To fix this, you need to issue the .html command on the specific container you need


Links

Your links won't work because Javascript can't bind to elements not present on DOM load

You'll typically have something like this:

$(".element").on("event", function() {
    //Your stuff here
});

The problem here is because .element won't exist in your document before your Ajax call, it won't be bound, and consequently prevent your events from triggering actions. To get around this, you need to delegate from an element which will be present at DOM load, like this:

$(document).on("event", ".element", function() { 
    //Your Code
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top