简体   繁体   中英

Creating post with ajax in laravel

Hello everyone i'm having some problems with ajax and actually i'm pretty new with jquery and ajax, i have my comment system in laravel, thanks to Stackoverflow community i can edit and update the comments via ajax, however i can create a new comment but with php method only and i'm trying to create new comments with ajax.

this is my view:

<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>

here's my controller method store:

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);

}

Here's my ajax function:

    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);
    }
  });
});

I think this is useful, this is the ajax code that i'm using to update a comment "is working good".

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});
    });
});

My goal is to create a new comments without refreshing the whole page.

UPDATE

Token variable:

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

All you need is using serialize method for data and it is not important to determine 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
      }
  })

Try this:

   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!");
              }
       });

I'm not sure about your Controller. Why would you find Post? If the Comment belongs to a certain post (ie your post_id), you may have to include the post_id var in the ajax above if the post_id is a foreign key to your comments table, then do it like so in the controller:

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);
}

In the VerifyCsrfToken, place the post url:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM