jqueryajaxlaravel

live commenting system with laravel and ajax


I want to implement a live commenting system for each post of my project

this is my view

@extends('layouts.main')

@section('content')

    <p>{{ $post->title }}</p> // there is nothing wrong about showing post data

     <p>{{ $post->body }}</p>


    <div class = "row">
            <div class="col-md-6">
      <form id="company_form" method="POST" action = "{{ route('addComment') }}" class= "my-5">
                @csrf
               
                 <input type="hidden" name = "postId" id = "postId" value="{{ $post->id }}">  
              <div class="form-group my-2">
                    <input type="text" class="form-control" name = "name" id = "name" aria-describedby="emailHelp" required placeholder="your name">  
            </div>

             <div class="form-group my-2" >
                    <textarea class="form-control" name = "comment" rows="3" id = "comment" required></textarea>
            </div>
              <button class="btn btn-primary" id = "company_form_btn" type="submit">submit</button>
           
       </form>
            </div>
    </div>

this is my controller

public function addComment(Request $request){
        $comment = new Comment();
        $comment->postId = $request->postId;
        $comment->name = $request->name;
        $comment->comment = $request->comment;
        $comment->save();
        return response()->json(['success' => 'thanks for your comment']);
     }

and this is my ajax code

 $(document).ready(function(){
        $("#company_form_btn").click(function(e){
        e.preventDefault();
        var url = $(this).attr("action");
        let formData = new FormData(this);
        $.ajax({
                type:'POST',
                url: url,
                data: formData,
                contentType: false,
                dataType:'json',
                cache: false,
                processData: false,
               success:function(response){
                   alert(response.success)
                },
                error: function(response){
                   
                }
       });
    
});
    });
  

comment submitted and saved in database totally fine but i get this, and whole view goes away

view goes away

i want to achieve something like this

live comment

thanks for your help


Solution

  • I left this problem alone, and I was working on the other parts of my project

    last night i ran into a problem and google up the error message and i came up with this thread of stack overflow

    link

    I looked at the accepted answer(first answer) he wrote

    The problem was: I was using the slim build of jQuery,

    I was trying to figure out the solution for another problem, I decided to give it a shot, I replace the jquery CDN link with the one which is not slim version, and bam it worked!