在laravel

时间:2017-06-10 19:53:20

标签: javascript php jquery laravel

大家好,我对ajax有一些问题,实际上我是jquery和ajax的新手,我在laravel中有我的评论系统,感谢Stackoverflow社区我可以通过ajax编辑和更新评论,但是我可以创建一个新的评论,但只使用PHP方法,我试图用ajax创建新的评论。

这是我的观点:

<article class="row">
                            
                        <div class="col-md-8 col-sm-8">
                          <div class="panel panel-default arrow left">
                            <div class="panel-body">
                              <header class="text-left">
                                <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                                <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                              </header>
                              <div id="comment-post" data-commentid="{{ $comment->id }}">
                                  <p id="display-comment"{{ $comment->id }} class="store-comment">{{ $comment->comment }}</p>
                              </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                              @if(Auth::guest())

                              No puedes responder ningún comentario si no has ingresado.

                              @else

                              @if(Auth::user() == $comment->user)
                                <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
                              @endif

                              @if(Auth::user() != $comment->user)
                                <a href="#">Responder</a>
                              @endif

                              @endif
                            </div>

                          </div>
                        </div>
                      </article>

这是我的控制器方法商店:

public function store(Request $request, $post_id)
{

  $post = Post::find($post_id);

  $this->validate($request, [
      'comment' => 'required'
  ]);

  $comment = new Comment();

  $comment->comment = $request['comment'];

  $comment->save();
  return response()->json(['edit_comment' => $comment->comment, $post->id, 'success' => true], 200);

}

这是我的ajax功能:

    var urlCreate = '{{ url('comments/store') }}';


$('#create').submit(function(){
  var comentario = $('#add-comment').val();
  $.ajax({
    method: 'POST',
    url: urlCreate,
    data: {comentario: comment, _token: token, _method: 'PUT'},
    dataType: 'json'
  })
  .done(function(message){
    if (message.success === true){
      $(divcomment).find('.store-comment').text(commentario);
    }
  });
});

我认为这很有用,这是我用来更新评论的ajax代码&#34;工作正常&#34;。

var urlEdit = '{{ url('comments/update') }}';
    $('.edit-comment').click(function(event){
  event.preventDefault();
  divcomment = this.parentNode.parentNode;
  commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
  var commentBody = $(divcomment).find('#display-comment').text();
  $('#comment').val(commentBody);
  $('#edit-comment').modal();
});

$('#modal-save').on('click', function(){
    var $btn = $(this).button('loading');
    var comment = $('#comment').val();
    $(this).button('loading');
    $.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
            comment: comment,
            commentId: commentId,
            _token: token,
            _method: 'PUT',
         },
        dataType: 'json'
    })
    .done(function (msg){
        if (msg.success === true) {
            $(divcomment).find('#display-comment').text(comment);
        }
        $btn.button('reset');
        $('#edit-comment').modal('hide');
        success('Comentario editado.', '.alert .alert-success', {timeOut: 5000});
    });
});

我的目标是在不刷新整个页面的情况下创建新的评论。

更新

令牌变量:

    var token = '{{ Session::token() }}';

2 个答案:

答案 0 :(得分:0)

您只需使用serialize方法获取数据,确定dataType

并不重要
var urlCreate = '{{ url('comments/store') }}';
$('#create').submit(function(){
    var comentario = $('#add-comment').val();
    $.ajax({
      method: 'POST',
      url: urlCreate,
      data: $("#YourFormId").serialize(), 
      //dataType: 'json'
      success: function(){
         // show message and any logic
      },
      error: function(xhr, status, response){
         // In case of error use those params to produce informative message
      }
  })

答案 1 :(得分:0)

试试这个:

   var comment = $('#comment').val()
    , comment_id   = $('#comment-post').data('commentid')
 /* , post_id = $('#post_id').val() or {{ $post_id }} if you've passed it along */
   , urlEdit = '{{ url('comments/store') }}';

   $.ajax({
            type:'post',
            url:"urlEdit",
            data: {
                    comment: comment,
                    comment_id: comment_id
                },
            success:function(data){
                  /* reload element upon success */
            },
              error: function(data){
                 alert("Error Submitting Record!");
              }
       });

我对您的控制器不确定。你为什么找到Post? 如果Comment属于某个帖子(即你的post_id),如果post_id是你的注释表的外键,你可能必须在上面的ajax中包含post_id var,然后在控制器中这样做:

public function store(Request $request)
{
  $this->validate($request, [
      'comment' => 'required'
  ]);
  $comment = new Comment();
  $comment->comment = $request->comment;
  $comment->comment_id = $request->comment_id;
  $comment->post_id = $request->post_id; // only if included
  $comment->save();
  return response()->json([ 'code'=>200], 200);
}

在VerifyCsrfToken中,放置帖子网址:

protected $except = [
    '/comments/store'
];