skip to Main Content

POST http://127.0.0.1:8000/admin/upload/services 419 (unknown status) CSRF token mismatch

Even though it has csrf token, it still has error 419 (unknown status) CSRF token mismatch
……………………………


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

/* Upload file */
$("#upload").change(function(){
    const form = new FormData();
 
   console.log($(this)[0].files[0]);
   form.append('file', $(this)[0].files[0]);   
    $.ajax({
        url: '/admin/upload/services',
        processData: false,
        contentType: false,
        type: 'POST',
        dataType: 'JSON',
        data: form,
        success: function(results){
            if(results.error == false){
                $("#image_show").html(
                `
                <a href="${results.urlFile}" target="_blank">
                    <img src="${results.urlFile}" width="100px">
                </a>
                `);
                $("#thumb").val(results.urlFile);
            }
            else{
                alert(results.messageError);
            }
        }
    });
});

add.blade.php

@extends('admin.layout.main')

@section('header')
    <script src="/ckeditor/ckeditor.js"></script>
@endsection

@section('content')
    <form action="{{ route('product.store') }}" method="POST">
        @csrf
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="menu">Tên Sản Phẩm</label>
                        <input type="text" name="name" value="{{ old('name') }}" class="form-control"  placeholder="Nhập tên sản phẩm">
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="form-group">
                        <label>Danh Mục</label>
                        <select class="form-control" name="menu_id">
                            <option value=""></option>
                            {!! AppHelpersHelper::recursiveSelectMenu($menus) !!}
                        </select>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="menu">Giá Gốc</label>
                        <input type="number" name="price" value="{{ old('price') }}"  class="form-control" >
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="form-group">
                        <label for="menu">Giá Giảm</label>
                        <input type="number" name="price_sale" value="{{ old('price_sale') }}"  class="form-control" >
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label>Mô Tả </label>
                <textarea name="description" class="form-control">{{ old('description') }}</textarea>
            </div>

            <div class="form-group">
                <label>Mô Tả Chi Tiết</label>
                <textarea name="content" id="content" class="form-control">{{ old('content') }}</textarea>
            </div>

            <div class="form-group">
                <label for="menu">Ảnh Sản Phẩm</label>
                <input type="file" class="form-control" name="file" id="upload">
                <div id="image_show"></div>
                <input type="hidden" name="thumb" id="thumb">
            </div>

            <div class="form-group">
                <label>Kích Hoạt</label>
                <div class="custom-control custom-radio">
                    <input class="custom-control-input" value="1" type="radio" id="active" name="active" checked="">
                    <label for="active" class="custom-control-label">Có</label>
                </div>
                <div class="custom-control custom-radio">
                    <input class="custom-control-input" value="0" type="radio" id="no_active" name="active" >
                    <label for="no_active" class="custom-control-label">Không</label>
                </div>
            </div>

        </div>

        <div class="card-footer">
            <button type="submit" name="submit" class="btn btn-primary">Thêm Sản Phẩm</button>
        </div>
    </form>
@endsection

@section('footer')
    <script>
        CKEDITOR.replace('content');
    </script>

@endsection

header.blade.php

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ $title }}</title>

    <link rel="stylesheet"
        href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">

    <link rel="stylesheet" href="/template/admin_asset/plugins/fontawesome-free/css/all.min.css">

    <link rel="stylesheet" href="/template/admin_asset/plugins/icheck-bootstrap/icheck-bootstrap.min.css">

    <link rel="stylesheet" href="/template/admin_asset/dist/css/adminlte.min.css?v=3.2.0">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/adminlte.min.css">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.5.2/css/all.css">

    <meta name="csrf-token" content="{{ csrf_token() }}">
    @yield('header')
    

web.php

   Route::middleware('auth')->group(function () {
    Route::prefix('admin')->group(function () {
                Route::post('/upload/services', [UploadController::class, 'store']);
   });
});

Does anyone know the problem is ? Im stuck with this trouble for hours

2

Answers


  1. You can try to put the token in the input field:

    form.append('_token', document.querySelector('meta[name=csrf-token]').content);
    
    Login or Signup to reply.
  2. Ensure the meta tag with the CSRF token is present in the HTML head section.
    If the script runs before the meta tag is loaded, it won’t find the CSRF token. Make sure your script runs after the DOM is fully loaded or place it at the bottom of the HTML body.

      const csrfToken = $('meta[name="csrf-token"]').attr('content');
    
    if (!csrfToken) {
        console.error('CSRF token not found!');
        return;
    }
    
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': csrfToken
        }
    });
    
    console.log('CSRF Token:', csrfToken);
    
    /* Upload file */
    $("#upload").change(function(){
        const form = new FormData();
        const file = $(this)[0].files[0];
        
        if (!file) {
            console.error('No file selected!');
            return;
        }
    
        console.log('File selected:', file);
        form.append('file', file);
    
        $.ajax({
            url: '/admin/upload/services',
            processData: false,
            contentType: false,
            type: 'POST',
            dataType: 'JSON',
            data: form,
            success: function(results){
                if(results.error === false){
                    $("#image_show").html(`
                        <a href="${results.urlFile}" target="_blank">
                            <img src="${results.urlFile}" width="100px">
                        </a>
                    `);
                    $("#thumb").val(results.urlFile);
                } else {
                    alert(results.messageError);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('AJAX error:', textStatus, errorThrown);
            }
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search