skip to Main Content

I am trying to add comments to a post using ajax and laravel7
At the bottom of the post show blade template i include this part to display existing comments and a form to add a new one

<div class="container comments" #id="commentaires">
    <h2 class="comments-title">Commentaires des adhérents</h2>
    
    @foreach ($comments as $comment)
        <div class="comment-header">
            Posté par
            {!! AppUser::find($comment->agent_id)->firstname; !!}
            {!! AppUser::find($comment->agent_id)->familyname; !!}
            
            le
            <?php CarbonCarbon::setLocale('fr');?>
            {{CarbonCarbon::parse($comment->created_at)->translatedFormat('l jS F Y')}}
        </div>
        <div class="comment-body">
            {{$comment->content}}
        </div>
    @endforeach
    @auth
        <div class="comment-form">
            <div class="comment-invite">
                Laissez un commentaire
            </div>
            {!! Form::open(['action'=>"CommentController@store",'method'=>'POST']) !!}
                <div class="row post-option-background">
                    <div class="col-md-12" >
                        {{ Form::hidden('post_id', $post->id) }}
                        {{ Form::hidden('agent_id', auth()->user()->id) }}
                         {{ Form::text('content','',['class'=>'form-control'])}}
                    </div>
                </div>
                {{Form::submit('Enregistrer',['class'=>'btn btn-primary btn-submit'])}}

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

        </div>
    @endauth
    @guest
        <div class="comment-invite">
            Connectez-vous pour laisser un commentaire
        </div>
    @endguest
</div>

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        }
    });

    $(".btn-submit").click(function(e){
        e.preventDefault();
        var post_id = $("input[name=post_id]").val();
        var agent_id = $("input[name=agent_id]").val();
        var content = $("input[name=content]").val();
        console.log('post_id is : '+post_id+', agent_id is : '+agent_id+' and content is : '+content);
        var url='{{ url('comments') }}'
        console.log(url);
        $.ajax({
            type:'POST',
            url:url,
            data:{post_id:post_id, agent_id:agent_id, content:content},
            dataType: 'json',
            success:function(data){
                 $("#commentaires").append("<div> success </div>");
                 console.log('success');}
        });
        console.log('reaching end of click function');
    });
</script>

ROUTES

My routes are

Route::resource('posts','PostsController');
Route::post('/comments','CommentController@store')->name('storeAjax');

My store function in CommentController is

/**
 * Store a newly created comment in storage.
 *
 * @param  IlluminateHttpRequest  $request
 * @return IlluminateHttpResponse
 */
public function store(Request $request){
    if ($request->ajax()){
        $this->validate($request, [
        'content'=>'required',
        'post_id'=>'required',
        'agent_id'=>'required'
        ]);
            return response()->json(['success'=>'Got Simple Ajax Request.']);
    } else{
        return 'request is not ajax';
    }
}

I display the post, fill the comment form with : ‘This is an example’ and click submit button.

The click function is executed and I can see the various messages in the console

post_id is : 131, agent_id is : 1 and content is : This is an example
131:303:21 http://localhost:8000/comments 131:305:12 reaching end of
click function

Nevertheless, nothing happens in the browser. It seems that the ajax request is not executed.
Can somebody help me fixing this ?

2

Answers


  1. The problem might be Laravel’s CSRF protection. You can confirm this by looking in the Network panel of your browser’s dev tools (e.g. Firefox or Chrome). If submitting the form creates a new entry with status 419 then it’s a CSRF problem.

    You need to add the CSRF token to your HTML (usually in a meta tag) and send that token with your POST request.

    Add this in your <head>:

    <meta name="csrf-token" content="{{ csrf_token() }}">
    

    Add this to your main JS file (e.g. bootstrap.js)

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    

    Source: https://laravel.com/docs/7.x/csrf#csrf-x-csrf-token

    If that doesn’t fix it have a look in the Laravel error log.

    Login or Signup to reply.
  2. try

    $(document).on('button.btn-submit','click',function(e) {
    
    e.preventDefault();
    //rest of your code
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search