mercredi 5 juin 2019

Laravel submit form with ajax not working inside td tag

I have a table that displays upcoming tournaments with a 'enter tournament' button in the last td element of each row as shown below.

<td>
    <form class="entertournament" method="POST" action="">                       
        <input type="hidden" name="tournamentid" value="">
        <button class="btn btn-label-success btn-sm btn-upper btn-submit-entertournament">accept</button>
    </form>
</td>

Below is the javascript used to submit the form

<script type="text/javascript">

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

            $(".btn-submit-entertournament").click(function(e){
                e.preventDefault();

                let form = $(this).closest('form');
                console.log(form);
                $.ajax({
                    type:'POST',
                    url: form.attr('action'),
                    data: form.serialize(),

                    success:function(data){
                        if(data.successful) {
                            toastr.success(data.successful);
                        }
                    }
                });

            });

</script>

If I place the form outside of the table the form will submit fine and display the toastr notification that is returned from the controller as expected.

However when placing the form inside the td element I get redirected to /enterTournament when submitting the form and a 419 | page expired error is displayed.

I then include @csrf under the form (even though I think this is strange because I know I have the csrf specified in my head - hence why the form submits fine when it is outside the table).

Now when I try submit the form once again I get redirected to /enterTournament but this time with a JSON response: {"successful":"Tournament entered"}. This is the response that should be displayed through the toastr notification without a page redirect when submitting the form.

Any ideas why this is happening when the form is placed inside a td tag?



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2KAUK4G
via IFTTT

Aucun commentaire:

Enregistrer un commentaire