0

I am A PHP developer and currently moving towards Laravel framework as per my task I have to complete the real-time table using ajax but I am sticking with an error which is CSRF token mismatch error please help me to resolve the error I am posting shortcode only

ajax

$(document).ready(function(){
            $('.toggle-class').change(function() {

                var status = $(this).prop('checked') === true;
                var id = $(this).data('id');
                var csrf=$('meta[name="csrf-token"]').attr('content');



                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: '/package/status',
                    data: {'status': status, 'id': id, 'XSRF-TOKEN': csrf},
                    success: function(data){
                        console.log('success '+data);
                    }
                });

            })
        })

Route Path

Route::post('package/status', [App\Http\Controllers\PackageController::class,'status']);

Controller code

 public function status(Request $request){


        $Package = package::find($request->id);

        $Package->status = $request->status;

        $Package->save();

        return response()->json(['success'=>'Status change successfully.']);
    }

I don't know why it is showing me CSRF token mismatch when headers contain tokens once solved I can have some real-time action.

4 Answers4

1

Try this:

 data: {'status': status, 'id': id, '_token': '{{csrf_token()}}'},
Mohammed_40
  • 432
  • 2
  • 9
0
<head>
   ..  .. .. 
    <meta name="csrf-token" content="{{ csrf_token() }}">
   ..  .. .. 
</head>

Add this meta tag in the header of your master layout for csrf token which will be matched with the csrf token of your ajax call and thus it will solve your problem hopefully. Let me know if it works.

Farhan Ibn Wahid
  • 926
  • 1
  • 9
  • 22
0
$.ajax({
    type: "POST",
    dataType: "json",
    url: '/package/status',
    data: {'status': status, 'id': id, '_token': '{{ csrf_token() }}'},
    success: function(data){
    console.log('success '+data);
    }
});

Change XSRF-TOKEN to _token And change data like this {{ csrf_token() }}

0

Just use _token for the csrf variable

        $(document).ready(function(){
            $('.toggle-class').change(function() {

                var status = $(this).prop('checked') === true;
                var id = $(this).data('id');
                var csrf=$('meta[name="csrf-token"]').attr('content');



                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: '/package/status',
                    data: {'status': status, 'id': id, '_token': csrf},
                    success: function(data){
                        console.log('success '+data);
                    }
                });

            })
        })
 
 
Jesus Erwin Suarez
  • 1,571
  • 16
  • 17