Home > Back-end >  My laravel & ajax form is returning error 419
My laravel & ajax form is returning error 419

Time:06-26

So e.preventDefault() isn't working for some reason. I have a foreach that repeats a question form. I tried onsubmit on the form & onclick on the submit button alternately. it isn't working for some reason.

here is my form


  @php
     $x = 0;
  @endphp
  @foreach ($knowledges as $know)
                   <div >
                        <label for="answers">الاجابه</label>
                        <form action="{{ route('user.knowledge.store', [$know->id]) }}" method="post"
                            onsubmit="handleForm(event,$i)" id="answerForm{{ $i }}">

                            <input type="hidden" value="{{ auth()->user()->id }}" name="user_id" id="user_id">

                            <input type="hidden" value="{{ $know->id }}" name="knowledge_id" id="question_id">


                            @for ($i = 0; $i <= 3; $i  )
                                <div >
                                    <div >
                                        {{ $know->answer[$i]['value'] }}
                                    </div>
                                    <div >
                                        <input type="checkbox" name="answer[{{ $i }}][key]" value="1">
                                    </div>
                                </div>
                            @endfor
                            <button  href="#" role="button" type="submit"> سجل
                                الاجابه</button>
                        </form>
                    </div>
                </div>
                </form>



                <hr>
                @php
                    $i  ;
                @endphp
            @endforeach

Here is my ajax

  function handleForm(event, id) {
            event.preventDefault();

            formId = 'answerForm'   id;
            var method = $(formId).attr('method');
            var action = $(formId).attr('action');

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                type: 'post',
                url: action,
                data: $(formId).serialize(),
                dataType: "json",
                success: function(response) {

                }
            });
        }


Here is a picture of the error enter image description here

CodePudding user response:

add the following script next to jquery library and before your script

<!-- check Xsrf Token -->
<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>
  • Related