1

In routes/api.php I have the following route:

Route::post('/session/storeValue', 'HomeController@storeValue');

And in controller I have AJAX function:

<script>

        function noviArtikal() {

  var data = { name: 'User');

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

  $.ajax({
    type: "POST",
    url: '/session/storeValue',
    data: data,
    success: function() {
      console.log("Valueadded");
    }
  });

        };
</script>

But keep getting error page not found when sending AJAX call. What am I doing wrong?

Gogo
  • 575
  • 2
  • 7
  • 20

4 Answers4

4

As it is api.php, it automatically adds /api/ to your URL. Try /api/session/storeValue.

From docs:

Routes defined in the routes/api.php file are nested within a route group by the RouteServiceProvider. Within this group, the /api URI prefix is automatically applied so you do not need to manually apply it to every route in the file. You may modify the prefix and other route group options by modifying your RouteServiceProvider class.

EDIT:

add name:

Route::post('/session/storeValue', 'HomeController@storeValue')->name('custom_name');

Then modify your javascript:

$.ajax({ type: "POST", url: '/session/storeValue', data: data,

to

$.ajax({ type: "POST", url: '{{ route('custom_name')}}', data: data,

EDIT 2: And yes, don't send CSRF_TOKEN (check @Yur Gasparyan answer)

Aleksandrs
  • 1,488
  • 1
  • 14
  • 34
4

For first you dont need to send CSRF_TOKEN to api. There is no sense to check CSRF-TOKEN because it is an api. Also to send request to api you need to add api prefix manualy.

Yur Gasparyan
  • 664
  • 5
  • 20
  • If I change to Route::post('api/session/storeValue', 'HomeController@storeValue'); and url: 'api/session/storeValue', if you mean like that I get localhost/appname/public/api/session/storeValue called. – Gogo Oct 29 '18 at 10:48
  • You dont need to change ` Route::post('session/storeValue', 'HomeController@storeValue')` to ` Route::post('api/session/storeValue', 'HomeController@storeValue')`. You need to move your routes in `routes/api.php` – Yur Gasparyan Oct 29 '18 at 11:33
0

add this code in your route/web.php

Route::post('/session/storeValue', 'HomeController@storeValue');
Shailendra Gupta
  • 1,054
  • 6
  • 15
0

simply give any name to the route just like this:

Route::post('/session/storeValue', 'HomeController@storeValue')->name('somename');

and in your ajax call just change the url attribute to: url: '{{ route('somename')}}',

Laravel attach /api to the api routes automatically through RouteServiceProvider and it is found is /Providers folder.

Also you don't need csrf_token when you are making an Api call.

Naveed Ali
  • 1,043
  • 7
  • 15