I cannot get json responses from cakephp3 controller

Hi all, i want to ask for your advice on what i am doing wrong
what i am trying to do is making an ajax call and getting any type of response from the controller. the response will be displayed in the page that initiated the ajax call but the controller never sends data back. what is weird is that the debug_kit detects the response and displays it so i get the _serialize and the result variable but not the javascript function

this is the javascript function:
<script type = "text/javascript" language = "javascript"> $(document).ready(function(){ $("button").click(function(){ $.ajax({ type : "GET", url : "<?php echo $this->Url->build(['controller' => 'users', 'action' => 'getByCategories', '_ext' => 'json']); ?>", contentType : false, processData : false, dataType : 'json', success: function(response){ console.log(JSON.parse(response)); } }); }); }); </script>

this is the action in the controller
public function getByCategories() { $id = 33; $this->autoRender = false; $cat = $this->Users->Categories->get($id); if ($this->Users->Categories->childCount($cat) > 0) { $result = $this->Users->Categories->find('all', ['conditions' => ['parent_id' => $id]]); $this->set(compact('result')); $this->set('_serialize', ['result']); } else { $result['Machines'] = $this->Users->Machines->find('all', ['conditions' => ['category_id' => $id]]); $result['Medias'] = $this->Users->Medias->find('all', ['conditions' => ['category_id' => $id]]); $this->set(compact('result')); $this->set('_serialize', ['result']); } }

if i try to access the link of this action i get null

i added the routes for the json extension
i loaded the request handler component.

the debug kit receives the response but not the javascript function

thanking you in advance

I think you’re not rendering the view at all, so it’s normal that nothing is displayed.

You can try to add die(json_encode($result)) instead of $this->set(compact(‘result’));
That should give you the expected results.

Thank you ali this did the trick but i want to ask you if i want to use the _serialize how should i do it. Because i read somewhere that i need to disable the view so i can get the result in the same page that is making the request

Did you added json handling at your /config/routes.php file?


1 Like

You can test RESTful operations using the fiddler tool to determine if your creating any json data. This will allow you to concentrate on only the data being retrieved to better isolate the problem.

Thanks but yes i added it and btw ali’s response did the trick
thanks again

the problem was that i was not getting any response back so the problem was in the cakePHP action

thanks for the update