Mr. Pyramid Mr. Pyramid - 1 year ago 135
Ajax Question

Getting MethodNotAllowedHere on AJAX call to Laravel controller

I am trying to call controller from AJAX and there I got this error

MethodNotAllowedHttpException in RouteCollection.php line 218:


I've tried a lot but not able to trace the actual problem.

Route.php

/*Ajax Request for Category*/
Route::post('category','[email protected]');
Route::post('category/{category}', '[email protected]');


header.blade.php

<script>
$(document).ready(function(){
$.ajax({
method:'post',
url:'/category',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
//$("#msg").html(data.msg);
alert(data.category_name);
}
});
});
</script>


AjaxOperationController.php



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;

class AjaxOperationController extends Controller
{
public function category(){
$category=DB::select('select category_name from categories');
echo $category;
return response()->json(array('category_name'=> $category));
}
}

Answer Source

Add the csrf token to a meta:

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

Set up .ajaxSetup (This will be set in the default template so its included everywhere for other ajax requests):

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

Your ajax:

$(document).ready(function(){
    $.ajax({
       type:'post',
       url:'/category',
       success:function(data){
          //$("#msg").html(data.msg);
          alert(data.category_name);
       }
    });
 });

Keep track of your network tab in inspect element to see what response you get from the request, this will help debug further if anything else is going wrong

EDIT

Change your success response to:

success:function(data) {
    for (var i = 0; i < data.length; i++) {
        $('#msg').append(data.category_name[i].category_name)
    }
}

Controller namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Categories;

 class AjaxOperationController extends Controller 
 {
 public function category(){
    $categories = Categories::get();
    return response()->json($categories);
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download