Laravel AJAX NotFoundHttpException

771 views Asked by At

I've been trying to use the AJAX in my laravel project but it always return an error,

NotFoundHttpException on RouteCollection.php", "line": 179

My route in web.php is

Route::post('/ajaxRequest','AjaxController@index');

The controller code is

class AjaxController extends Controller {
   public function index(){
      $msg = "Ajax test message";
      return response()->json(array('msg'=> $msg), 200);
   }
}

The Ajax call which I've used is

    $.ajax({
             type:'POST',
             url:'{{url("/ajaxRequest")}}',
             datatype:'json',
             data: pass,
             success:function(data){
                $("#result").html(data.msg);
              }
            }).fail(function (jqXHR, textStatus, error) {
                // Handle error here
                $("#result").html(jqXHR.responseText);
});

and used the meta tag content for csrf_token

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

And retrieved the value using

var pass={'_token': $('meta[name="csrf-token"]').attr('content')};

Please help me to resolve this error.

2

There are 2 answers

2
Exterminator On BEST ANSWER

change route to this

Route::post('/ajaxRequest','AjaxController@index')->name('routeName');

and in ajax request make following changes:

 $.ajax({
             type:'POST',
             url:'/ajaxRequest',  //if in js file
             url:'{{route("routeName")}}',  //if in blade file 
             datatype:'json',
             data: pass,
             success:function(data){
                $("#result").html(data.msg);
              }
            }).fail(function (jqXHR, textStatus, error) {
                // Handle error here
                $("#result").html(jqXHR.responseText);
});
0
Emtiaz Zahid On

Call route using route name

Route file

Route::post('/ajaxRequest','AjaxController@index')->name('ajaxRequest');

And your ajax request

 $.ajax({
             type:'POST',
             url:'{{route("ajaxRequest")}}',
             datatype:'json',
             data: pass,
             success:function(data){
                $("#result").html(data.msg);
              }
            }).fail(function (jqXHR, textStatus, error) {
                // Handle error here
                $("#result").html(jqXHR.responseText);
});