Ajax Post request being called twice in Laravel

  ajax, laravel

I was searching stackoverflow for this issue but none of them worked. I have a subscribe button in my blade template where it is shown below along my ajax code:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div class="flash-message"></div>
            <div class="card">
                <div class="card-header">
                    <div class="level">
                        <span class="flex"><a href="{{route('profile',$thread->creator->name)}}">{{$thread->creator->name}}</a> posted:
                            {{$thread->title}}
                        </span>
                        @if(auth()->check())
                        @if($subscription)
                        <button class="btn btn-secondary" id="unsubscribe">Unsubscribe</button>
                        @else
                        <button class="btn btn-danger" id="subscribe">Subscribe</button>
                        @endif
                        @endif
                        @can('update',$thread)
                        <a href="{{$thread->path()}}/edit" class="btn btn-link">Edit Thread</a>
                        <form action="{{$thread->path()}}" method="POST">
                            @csrf
                            @method('delete')
                            <button class="btn btn-link" type="submit">Delete Thread</button>
                        </form>
                        @endcan
                    </div>
                </div>
                <div class="card-body">
                {{$thread->body}}
                </div>
            </div>
            @foreach($replies as $reply)
             @include('threads.reply')
            @endforeach
            <div class="mt-5">
                {{$replies->links()}}
            </div>
            @if(auth()->check())
            <form method="POST" action="{{$thread->path() . '/replies'}}">
               @csrf
               <div class="form-group mt-2">
                   <textarea class="form-control @error('body') is-invalid @enderror" name="body" id="body" rows="5" placeholder="Write a reply"></textarea>
                   @error('body')
                    <div class="alert alert-danger">{{ $message }}</div>
                    @enderror
               </div>     
               <div class="d-flex justify-content-between">
                   <button type="submit" class="btn btn-dark">Post</button>        
                    <i class="fas fa-share pr-4">Share:</i>      
               </div>  
               <div class="d-flex justify-content-end ">
                <a href="https://www.facebook.com/sharer/sharer.php?u={{url()->current()}}" target="_blank"><span class="fab fa-facebook-square fa-3x pr-2" style="color:#3b5998"></span></a>
                <a href="https://twitter.com/intent/tweet?url={{url()->current()}}" target="_blank"><span class="fab fa-twitter fa-3x pr-2" style="color:#00acee"></span></a>
                <a href="https://wa.me/?text={{url()->current()}}" target="_blank" ><span class="fab fa-whatsapp-square fa-3x" style="color:#4FCE5D"></span></a>
               </div>
            </form>      
             @else   
             <p>Please <a href="{{route('login')}}">sign in</a> to participate in the forum</p> 
            @endif
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <p>
                        This thread was posted {{$thread->created_at->diffForHumans()}}
                        by <a href="#">{{$thread->creator->name}}</a>
                        and has {{$thread->replies_count}} {{Str::plural('comment',$thread->replies_count)}}
                    </p>
                </div>
            </div>
        </div>
    </div>  
</div>

<script type="application/javascript">

    $(document).ready(function(){
        $('#subscribe').click(function(e){
            e.preventDefault();
            $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                  }
              });
            $.ajax({
                url: "{{route('subscription.store')}}",
                method:'POST',
                data: {
                    thread_id: "{{$thread->id}}",
                },
                success:function(response){
                    $('div.flash-message').html(response);
                },
                error:function(error){
                    console.log(error);
                }
            });
        });
    });

</script>
@endsection

And this is my SubscriptionController:

  public function store(Request $request){
        
        $subscription = Subscription::create([
            'thread_id' => $request->thread_id,
            'user_id' => auth()->id()
        ]);

        Session::flash('success', 'You have subscribed to this thread');
        return view('partials.flash-messages')->render();
    }

What is supposed to happen when I click subscribe is that I will hit the store controller and a new record will be created in my subscriptions table. Upon clicking it, I found out that the post request was called twice on my network tab(dev tools) with no error or such and found two identical records being inserted to my table.

I might have overlooked over something but couldn’t find my mistake. How do I fix this?

Source: Laravel

Leave a Reply