AppController
$this->loadComponent('RequestHandler');
routes.php
$builder->scope('/api', function (RouteBuilder $router) { $router->setExtensions(['json', 'pdf']); $router->connect('/get-price', ['controller' => 'Api', 'action' => 'getPrice']); });
class ApiController extends AppController { public function getPrice() { if( $this->request->is('ajax') ) { $coin = $this->request->getParsedBody()['id']; if( array_key_exists($coin, $this->coins) ) { $client = new CoinGeckoClient(); $result = $client->simple()->getPrice($coin, 'usd,pln'); } else { $result = ['error' => 'Niepoprawny symbol kryptowaluty']; } $this->set('result', $result); $this->viewBuilder()->setOption('serialize', ['result']); } } }
javascript
function setCryptoPrices (coin='') { var url = '/api/get-crypto-price.json'; $.ajax({ url : url, type : 'post', dataType : 'json', data : {id : coin}, success : function(resp){ renderCryptoPrices(resp.result[coin], side); }, error : function(e){ console.error(e); } }); }