3

I've been reading through some posts on SO to see how others are handling this and the implementation I am using is almost there but fails after the third link requested. What happens is the page is reloaded as opposed to firing the ajax request. I have also removed Turbolinks but that hasn't made a difference.

This is my setup and I think the JS is failing somewhere. My jQuery is not that strong.

Index.html.erb

<div class="facebook_ajax">
  <%= render 'shared/posts' %>
</div> 

shared/_posts.html.erb

<% @posts.each do |p| %>
<article class="post">
<%= image_tag('/assets/vandals_fb_profile.jpg') %>
<%= link_to 'Varsity Vandals', "https://www.facebook.com/VarsityVandals", target: 'blank' %>
<%= date_output(p.created_time) %>
  <figure>
    <% if p.large_image_url? %>
      <%= image_tag(p.large_image_url) %>
    <% end %>

    <% if p.video_url? %>
      <%= raw youtube_embed(p.video_url) %>
    <% end %>
  </figure>
  <p><%= p.message.gsub("\n", "<br>").html_safe %></p>
    <% if p.description? %>
      <p><%= p.description %></p>
    <% end %>
    <%= link_to 'Read More', p.link %>
</article>
<hr/>
<% end %>
<%= will_paginate @posts, previous_label: '',  next_label: '', page_links: false %>

index.js.erb

$('.facebook_ajax').html("<%= escape_javascript(render("shared/posts"))%>")

jQuery

<script>
      $(document).ready(function () {
        $(".facebook_ajax .pagination a").on("click", function(){
          $.getScript(this.href);
          return false;
        });
      });
    </script>

So when clicking the next link for the first time ajax request completes fine, but upon the third click the page reloads and the URL is changed to ?_=1399027258398&page=3.

How can I combat this?

1 Answer 1

5

Thought I would answer this so maybe it can help someone else, I had to delegate the event to a DOM element that was always there, so used the body tag for example

$(document).ready(function () {
        $("body").on("click", '.facebook_ajax .pagination a', function(e){
          e.preventDefault();
          $.getScript(this.href);
          return false;
        });
      });

My understanding that is once the first click is made you lose the oriiginal set of href's that where gathered

Good link Here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.