2
votes

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
Do you have any problem if you call route using route name?Emtiaz Zahid
'{{url("/ajaxRequest")}}' - This might not be having the effect you think it should be having if you are in a JS file (external to your blade).Script47
use url:'/ajaxRequest', instead if you have your ajax code in seperate js file as suggested by @ExterminatorLeena Patel
Welcome. Use your browser console/Network tab to make sure the request is correct. You can also use php artisan route:list to make sure your route is in the system. (Use php artisan route:cache to reload/cache your routes file)brombeer

2 Answers

1
votes

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
votes

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);
});