CodeIgniter Forums
Ajax get request works, but post fails, same url. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Ajax get request works, but post fails, same url. (/showthread.php?tid=75565)



Ajax get request works, but post fails, same url. - jottinger - 02-21-2020

I've changed the following files:








app/Config/Autoload.php (added 'Modules')

Code:
$psr4 = [
   'Config'      => APPPATH . 'Config',
   APP_NAMESPACE => APPPATH,                // For custom namespace
   'App'         => APPPATH,                // To ensure filters, etc still found,
   'Modules'      => ROOTPATH.'modules'
];

app/Config/Routes.php
Code:
$routes->group('navigation', ['namespace' => 'Modules\Navigation\Controllers'], function($routes)
{
   $routes->get('/', 'NavigationController::index');
   $routes->get('getnavigationitems', 'NavigationController::getNavigationItems');
});

The issue I am having is that if I do a simple jQuery ajax POST request like this, it fails:

Code:
$(document).ready(function(){
   $.post('navigation/getnavigationitems',{group:'admin'},function(response){
      console.log(response);
   })
})

I get "Controller or its method is not found: App\\Controllers\\Navigation::getnavigationitems"

But if I do the same request by changing $.post to $.get like this, it works:

Code:
$(document).ready(function(){
   $.get('navigation/getnavigationitems',{group:'admin'},function(response){
      console.log(response);
   })
})

No other default codeigniter 4 files have been modified.  What am I doing wrong?


RE: Ajax get request works, but post fails, same url. - jreklund - 02-21-2020

You have forced it into get(), and you are making a post().

https://codeigniter4.github.io/userguide/incoming/routing.html#using-http-verbs-in-routes

PHP Code:
$routes->group('navigation', ['namespace' => 'Modules\Navigation\Controllers'], function($routes)
{
   
$routes->post('/''NavigationController::index');
   
$routes->post('getnavigationitems''NavigationController::getNavigationItems');
}); 



RE: Ajax get request works, but post fails, same url. - jottinger - 02-21-2020

you rule. I didn't realize that was what ->get was and now I feel stupid. Thanks so much