Почему мой комментарий отображается как объект JSON и не добавляется в DOM - PullRequest
0 голосов
/ 16 февраля 2019

Я создаю комментарий с помощью Jquery и хочу добавить его на страницу без перезагрузки страницы.У меня есть функция-прототип commentConfirm, ловящая его перед публикацией.Я не могу использовать remote: true в этом проекте, поэтому вот код:

$(function createComment() {
  $("#new_comment").on("submit", function(e) {

    const values = {
      description: $('#comment_description').val(),
      rating: $('#comment_rating').val()
    };

    const newComment = new Comment(values);
    newComment.commentConfirm();

  });
});

function Comment(comment) {
  this.description = comment.description;
  this.rating = comment.rating;
}

Comment.prototype.commentConfirm = function(e) {
  let doIt = confirm(`You are about to comment: "${this.description}" and give a rating of: ${this.rating} stars`);
  if(!doIt)
    return;

  let params = {
    'comment[description]': this.description,
    'comment[rating]': this.rating
  };

  $.post(this.action, params).success(function(response) {

    $('div.comments_container').append('<div class="new_comment_' + `${response.id}` + '"> </div>')

      $('div.new_comment_'+ `${response.id}`).append('<h3 class="cheading">' + `${response.user.name}` + ' gives ' + `${response.rating}` + ' out of 5 stars! </h3>')
      $('div.new_comment_'+ `${response.id}`).append('<p class="cdescription">' + `${response.description}` + '</p>')
      $('div.new_comment_'+ `${response.id}`).append('<a class="ecomment" href="/recipes/' + `${response.recipe_id}` + '/comments/' + `${response.id}` + '/edit">Edit</a>' + " ")
      $('div.new_comment_'+ `${response.id}`).append('<a class="dcomment" rel="nofollow" data-method="delete" href="/comments/' + `${response.id}` + '">Delete</a>')

      $('form#new_comment')[0].reset();
    });
};

Не уверен, что это вызывает проблему, но вот моя функция создания в контроллере:

 def create
    if logged_in?
      comment = Comment.new(comment_params)
      comment.recipe = find_by_recipe_id
      comment.user = current_user
        if comment.description.empty? || comment.rating == nil
          redirect_to recipe_path(comment.recipe), alert: "Please fill out all fields"
        else
          comment.save
          render json: comment.to_json(only: [:rating, :description, :id, :recipe_id],
                                    include: [user: { only: [:name]}])

      end
    else
      redirect_to login_path, alert: "You must be logged in to comment"
    end
  end

Любая помощь с его проблемой будет принята с благодарностью !!

вот репо, если это поможет ответить на некоторые другие вопросы: https://github.com/Bartekswistak/fun_guy_chef/tree/jquery

Ответы [ 2 ]

0 голосов
/ 16 февраля 2019

Событие submit перезагружает страницу.Чтобы не дать перезагрузить страницу, запретите действие по умолчанию .Итак, ваша самая первая функция будет выглядеть так:

$(function createComment() {
  $("#new_comment").on("submit", function(e) {

    e.preventDefault();

    const values = {
      description: $('#comment_description').val(),
      rating: $('#comment_rating').val()
    };

    const newComment = new Comment(values);
    newComment.commentConfirm();

  });
});
0 голосов
/ 16 февраля 2019

Я не могу подтвердить, что остальная часть вашего кода работает правильно, но вам нужно обработать событие submit вручную, чтобы предотвратить перезагрузку страницы ...

$("#new_comment").on("submit", function(e) {
   e.preventDefault();

   ....
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...