简体   繁体   中英

how to add comment with ajax, without refresh to see a new comment in laravel

i was successfully added a new comment to database but why it must refresh page to see new comment. i confuse about this problem. where is part of my code that wrong?

here is my code.

route

Route::post('blog/{post}/comments/store', 'AuthMember\CommentController@store')->name('comment.add');

comment controller note: i use decode on post id using hash.

public function store(Requests\CommentStoreRequest $request)
{

    if($request->ajax()){
        $comment       = new Comment;
        $comment->body = $request->get('comment_body');
        $comment->user()->associate($request->user('member'));

        $key    = $request->get('post_id');
        $result = Hashids::connection('main')->decode($key)[0];
        $post   = Post::find($result);

        $post->comments()->save($comment);
        $response = array(
            'status' => 'success',
            'msg' => 'comment has been added',
        );
        return Response::json($response);

    }


}

form comment

{!! Form::open(array(
                            'route'  => ['comment.add', $post->slug],
                            'method' => 'POST',
                            'id'     => 'form',
                            'name'   => 'form',
                            'data-parsley-validate'))
                        !!}



                            <div class="form-group {{ $errors->has('comment_body') ? 'has-error': '' }}">
                                {!! Form::textarea('comment_body', null, array(
                                    'class'       => 'form-control elastic',
                                    'id'          => 'comment_body',
                                    'rows'        => '3',
                                    'name'        => 'comment_body',
                                    'placeholder' => 'Write Something...',
                                    'required', 'minlength="4"')
                                    )

                                !!}

                                @if($errors->has('comment_body'))
                                    <span class="help-block">{{$errors->first('comment_body')}}</span>
                                @endif


                                <input type="hidden" name="post_id" value="{{ $parameter }}" />
                            </div>

                            <div class="form-group">
                                {!! Form::submit('Submit', array(
                                    'name'    => 'submit',
                                    'class'   => 'btn btn-primary',
                                    'id'      => 'btnComments'
                                    )) !!}

                            </div>

                        {!! Form::close() !!}

ajax, so this is my ajax to store new comment into database

<script>
$(document).ready(function(){
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $('#form').on('submit', function(event) {
        event.preventDefault();
        var form = $(this);
        var url = form.attr('action');
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
        });
        $.ajax({
            // url: '{{route('comment.add',[$post->slug])}}',
            url: url,
            type: 'POST',
            data: form.serialize(),
            dataType: 'JSON',
            success: function (data) {
                console.log(data);
            },
            error: function(data){
                console.log(data);
            }
        });
    });
});
</script>

You are redirecting as :

return redirect()->to(app('url')->previous(). '#comments')->with('message-post', 'Comment has been added');

Try to return JSON as:

return response()->json(["success"=>"true", "message"=>"Comment has been added"]);

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