Home > Software engineering >  Regenerate CSRF Token If ajax request has an error
Regenerate CSRF Token If ajax request has an error

Time:10-25

I'm using ajax request to submit registration form. If a user submit form on first attempt with correct information, the request is working well. But If user made any mistake, correct the information and submit again, the data is inserted but in console.log(data), I'm facing this error:

"CSRF token mismatch."

"\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php". Line: 389.

head.blade.php

<meta name="csrf-token" content="{{ csrf_token() }}">

My Blade view:

$(document).ready(function() {
    $('#send_form').click(function(e) {
    e.preventDefault();
    /*Ajax Request Header setup*/
    $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });

    $('#send_form').html('Sending..');
        /* Submit form data using ajax*/
        $.ajax({
            url: "{{ route('register')}}",
            method: 'POST',
            data: $('#ajax-register-form').serialize(),

            success: function(response) {


            $('#send_form').html('Submit');

            document.getElementById("ajax-register-form").reset();


              },
            error: function(data) {
              var errors = data.responseJSON;
              console.log(errors);
              $('.error-warning').show();

              }
        });
    });
  });

If user has an error on first attempt, the csrf token should regenerate so user can submit the form without refreshing the whole page.

CodePudding user response:

Remove headers from $.ajaxSetup and put it in send_form request like this.

$('#send_form').html('Sending..');
        /* Submit form data using ajax*/
        $.ajax({
            url: "{{ route('register')}}",
            method: 'POST',
            headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: $('#ajax-register-form').serialize(),

            success: function(response) {


            $('#send_form').html('Submit');

            document.getElementById("ajax-register-form").reset();


              },
            error: function(data) {
              var errors = data.responseJSON;
              console.log(errors);
              $('.error-warning').show();

              }
        });
    });
  • Related