Model obsługi Ajax
Controller
use Cake\View\JsonView;
public function viewClasses(): array { return [JsonView::class]; }
public function getTotals() { if( $this->request->is('ajax') ) { $tr_table = $this->fetchTable("Transactions"); $q = $tr_table->find(); $q->select([ 'month' => 'MONTH(created)', 'pln' => 'SUM(CASE tr_type WHEN "sell" THEN wydano ELSE otrzymano END)', 'income' => 'SUM(income)' ]); $q->where(["YEAR(created)" => '2023']); $q->group(["MONTH(created)"]); $resp = $q->all(); $this->set('resp', $resp); $this->viewBuilder()->setOption('serialize', 'resp'); } exit; }
Javascript
$.ajax({ url: '/home/get-totals.json', type: 'post', success: function(resp){ if(resp) { console.log(resp); } else { console.log("Brak odpowiedzi"); } }, error: function(e){ console.log(e); } });