Reputation:
I'm trying to load the comment for each article on my index
page using AJAX.
What am I missing here?
Index:
#welcome/index.haml
- @articles.each do |article|
= article.title
- article.comments.each do |comment|
%comment-content{ :id => "comment-<%= comment.id %>", :class => "comment-block", "data-comment-id" => "<%= comment.id %>"}
Controller:
#comments_controller.rb
class CommentsController < ApplicationController
def show
respond_to do |format|
format.js { }
end
end
end
JS:
#comments.js
var loadComment;
loadComment = function() {
return $('.comment-block').each(function() {
var $comment_block;
$comment_block = $(this);
return $.ajax('/comments/show', {
type: 'GET',
dataType: 'script',
data: {
comment_id: $comment_block.data('comment-id')
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Worked OK!");
}
});
});
};
$(document).ready(loadComment);
$(document).on('page:change', loadComment);
Show:
#comments/show.js.erb
$('#comment-<%= @comment.id %>').append('j render(@comment.content)');
EDIT:
So the console log displays the following link but I guess the correct URL would be localhost:3000/articles/1/comment/1
How do I fix it?
Console log:
http://localhost:3000/show?comment_id=%3C%25%3D+comment.id+%25%3E&_=1457784667124
resources :articles do
resources :comments do
end
end
Upvotes: 0
Views: 290
Reputation: 891
If you change your loadComment function to this, it should work --
loadComment = function() {
return $('.comment-block').each(function() {
var $comment_block;
$comment_block = $(this);
comment_id: $comment_block.data('comment-id')
return $.ajax('/comments/'+comment_id+, {
type: 'GET',
dataType: 'script',
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return console.log("Worked OK!");
}
});
});
};
The route for the 'show' action is /comments/:comment_id
Upvotes: 2