Search code examples
ajaxlaravellaravel-8http-status-code-405

405 (Method Not Allowed) error on ajax in Laravel 8


I am trying to call an ajax function in my Laravel 8 Project. But on every call I am getting error POST http://127.0.0.1:8000/getReasonForVisit 405 (Method Not Allowed). I have tried many options like changing post method to get, change url etc. but no use. It would be helpful if someone can help me.

Here is my code.

JS File

function getReasonForVisit(catId) {
       
  $.ajaxSetup({
     headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
     }
  });
  $.ajax({
      type: 'POST',
      url : '/getReasonForVisit',
      data : {'catId' : catId },
      dataType: 'json',
        success:function(data) {
           console.log(data);
        }
  });
}

$('#treatment-category').on('change', function (){
   var catId = $(this).val();
   getReasonForVisit(catId);
});

View

<select class="form-control form-select" name="category" id="treatment-category">
                                        
   <?php $categories = App::make("App\Http\Controllers\AppointmentsController")->getTreatmentCategories(); ?>
   @foreach($categories as $cat)  
      <option value="{{ $cat->id }}">{{ $cat->category_name }}</option>
   @endforeach
</select>

Route

Route::post('/getReasonForVisit', [App\Http\Controllers\AppointmentsController::class, 'getReasonForVisit'])->name('getReasonForVisit');

Controller

class AppointmentsController extends Controller
{
    public function getTreatmentCategories() {
       $categories = DB::table('treatment_category')->get();
       return $categories;
    }

    public function getReasonForVisit() {
       echo 111;
    }
}

EDIT

I did cleared my route cache. now it's showing error CSRF token mismatch


Solution

  • I resolved my issue. Actually I am missing csrf meta tag in my blade. So Now I added this code in view blade file in the <head> tag.

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