1

I'm working on a blog commenting feature on a website but I am having some challenges getting the commenting ajax request feature to work.

Here's my code below

Form

    {!! Form::open(['id' => 'comment_form']) !!}
     <div>
     {!! Form::hidden('article_id', $article->id) !!}
    </div>
    <div>
     {!! Form::hidden('user_id', 1) !!}
     {!! Form::hidden('username','name') !!}
     {!! Form::hidden('email','fname.lname@mail.com') !!}
     {!! Form::hidden('password','**__**') !!}
     {!! Form::hidden('service_id', 1) !!}
   </div>
   <div class="form-group">
     {!! Form::textarea('comment', null, ['class' => 'form-control', 'placeholder' => "Keep your comments to less than 250 chars"]) !!}
   </div>
   <div class="form-group">
     {!! Form::submit('Post!',['class' => 'btn btn-primary form-control', 'id' => 'comment' ]) !!}
   </div>
    {!! Form::close() !!}

Then below is my Ajax request using jQuery

$('#comment_form').on('submit', function(e) {

    $.ajaxSetup({
        header:$('meta[name="_token"]').attr('content')
    });

    e.preventDefault(e);

    $.ajax({
        type: "POST",
        url: '/articles/comment',
        data: $(this).serialize(),
        dataType:'json',
        delay: 2000,
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log("Failure");
        }
    });
});

And the Receiving Controller snippet is shown below

public function enterComment(Request $request)
    {


        // First check that the commenter is logged in with the session controller
        // If not force the person to be logged in

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

        try{
            // I am supposed to use the user_id record which is in the session.
            // However since I don't have my session variable created and model working
            // I will use this
            $user = User::where('user_id',$request['user_id'])->firstOrFail();
        }
        catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            // Ask user to to register his details.
            // For action tomorrow
            $user = User::create(['username'=> $request['username'],'email' => $request['email'],'password' => $request['password'],'service_id' => $request['service_id']]);
        }
        // Register comment
        $comment = new Comment;
        $comment->comment = $request['comment'];
        $comment->article_id = $request['article_id'];
        $comment->user_id = $request['user_id'];
        $comment->published_at = Carbon::now();
        $comment->save();
        dd($comment,$user);

        return response()->json(['comment' => $comment->comment], 200);
    }

That's what I am troubleshooting now and unfortunately I have not been able to figure out what I am doing wrong. Please can anyone help me out with this.

UncleT
  • 77
  • 1
  • 9
  • Provide the `route.php` code also? – Mayank Pandeyz Mar 19 '17 at 12:06
  • This the route below `Route::get('articles', 'ArticlesController@index'); Route::get('articles/create','ArticlesController@create'); Route::get('articles/{id}','ArticlesController@show'); Route::post('articles/store','ArticlesController@store'); Route::post('articles/edit','ArticlesController@edit'); Route::post('articles/update','ArticlesController@update'); Route::post('articles/comment','ArticlesController@enterComment'); Route::post('articles/getcomments','ArticlesController@getComments');` – UncleT Mar 19 '17 at 12:11
  • What is the issue you are facing ? – Mayank Pandeyz Mar 19 '17 at 12:14
  • @Mayank The comments don't get written to the database. They don't persist. I keep getting the `500 (Internal Server Error)`. So I am trying to confirm if I am doing anything wrong. – UncleT Mar 19 '17 at 12:16
  • I don't find any thing wrong in first look – Mayank Pandeyz Mar 19 '17 at 12:20
  • That's the problem. I don't even know where to begin troubleshooting. – UncleT Mar 19 '17 at 12:22
  • just to remind, laravel by default use x csrf token for protection. so you need to pass the token generated via ajax header. see http://stackoverflow.com/questions/32738763/laravel-csrf-token-mismatch-for-ajax-post-request – arisalsaila Mar 19 '17 at 12:22
  • you can add exception for specific routes by modifying VerifyCsrfToken.php, but it is bad practice. see https://laravel.com/docs/5.4/csrf – arisalsaila Mar 19 '17 at 12:24
  • That is already done in `$.ajaxSetup({ header:$('meta[name="_token"]').attr('content') });` – Mayank Pandeyz Mar 19 '17 at 12:24
  • sorry, missed it – arisalsaila Mar 19 '17 at 12:25
  • What's laravel.log content ? Check last lines of laravel log storage/logs/laravel.log – Ahmad Rezk Mar 19 '17 at 12:30
  • @AhmadRezk here it is below `#66 /home/vagrant/Code/lucyjonah.com/public/index.php(53): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #67 {main} ` – UncleT Mar 19 '17 at 12:38
  • does your request in the dev tool hit `articles/comment` ? or will it reach the base url ? – M.Elwan Mar 19 '17 at 12:44
  • I don't really understand the question @M.Elwan – UncleT Mar 19 '17 at 12:48
  • when you hit submit does the form send a POST request to `articles/comment`? is it reaching the controller? does the request contain the expected data? – M.Elwan Mar 19 '17 at 12:50
  • I think so cause I get an error 500 internal server. The Failure part of my jQuery requests runs the console.log("Failure") – UncleT Mar 19 '17 at 12:54
  • if you're getting 500 error so you're sending a request to a non-existing Route so please open the DevTool in the browser and tell us what exact url your request is hitting. – M.Elwan Mar 19 '17 at 12:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/138455/discussion-between-m-elwan-and-unclet). – M.Elwan Mar 19 '17 at 13:02
  • @UncleT, please send the last error which start from #1. You sent the last one #66 – Ahmad Rezk Mar 19 '17 at 16:17
  • @M.Elwan already helped me out. I think there's a problem with my model and JSON response – UncleT Mar 19 '17 at 18:38
  • @M.Elwan it's 5.2. I will fix it and post the solution. Thanks – UncleT Mar 19 '17 at 20:15

1 Answers1

0

There were a couple of issues. One was the way I was accessing the form data. I changed my request collection approach to $request->input(), which generated an array of all the items from the form. Then in the jQuery ajax function I changed the data collection method to

data:$(this).serializeArray().

This made the data easy to parse in the controller. Finally I changed the return response()->json(['comment' => $comment->comment], 200); to a simple return json_encode($request['comment']);

Thanks everyone for your help.

UncleT
  • 77
  • 1
  • 9