Skip to content Skip to sidebar Skip to footer

Show Partial In The Same Page Using Ajax Request

I'm new to rails and i'm trying to do a simple project for school. I have generated a scaffold as follows to begin. rails generate scaffold Book title:string content:text code:st

Solution 1:

Rails 5.1 doesn't have a dependency on jQuery. This code:

$('#content').html("<%= j (render 'books') %>");

is jQuery code. If you add the jquery-rails gem and follow the documentation, your code should work.

Solution 2:

I'm not sure where the problem lies with your code but I can suggest what, to me, is a more elegant alternative. I suggest binding a jquery onClick handler to your link and have it perform an ajax request to the server - either to a different view or re-code the same view - that sends back a json object containing all of your data the ajax success handler can then manipulate the html within the page. Something like this:

$("#all_books_link").click(function() {
  $.ajax({
     dataType: "json",
     url: <PUT ALL BOOKS SERVER URL HERE>,
     success:function(data) {
        for (var key in data) {
           $("#content").append("<div>"+data[key]+"</div>"
        }
     }
   });
});

Your server-side rails function should return a json object, not actual HTML.

Post a Comment for "Show Partial In The Same Page Using Ajax Request"