Saturday, April 1, 2017

Fetching comments of a post through ajax from database in laravel 5.3

<script>
    var token = '';
    var commentUrl = '';
    var fetchComments = '';

</script>  

A 'post' route to fetch comment

Route::post('comm', [
                'uses' => 'CommentController@comment',
                'as'   => 'commentT'
            ]);

function which has ajax

function getCommentsFromDb(postid){

    console.log("Post"+postid);
    $.ajax({

        type : 'POST',
        url  : fetchComments,
        data : { postid: postid,_token: token },
        success : function(result){
            console.log(result);
        }

    });

}

I am trying to fetch comments of a single post and i am passing id of post

 public function comment(Request $request)
    {
        //

            $answer_id = $request['answerid'];

            // echo "controller side ".$test;

            $comments = DB::table('posts')
                        ->join('posts', 'posts.id' , '=', 'comments.answer_id')
                        ->join('users' , 'users.id' , '=', 'comments.user_id')
                        ->where('posts.id', '=' , $post_id)
                        ->select('comments.comment as comment',
                                'comments.created_at as created_at',
                                'users.first_name as first_name',
                                'users.last_name as last_name',
                                'posts.post as post')
                        ->orderBy('created_at', 'desc')
                        ->get();

                   $comm = json_decode($comments);

                   print_r($comm);

        *// I though here i have to write html content which i want to render on the view* 


    }

I am getting expected result in console but how can i render this result to my view , it is simple if i do in core php but here in laravel i am stuck

In future i would be making delete,edit functionality for comments using ajax



via waq

Advertisement