I am currently creating a mobile application. I am using cakephp2.0 as my backend to handle the request and response. I would want cakephp to handle the request and send a json response back to the mobile application (application craft).
(1) For users controller, i did this:
public function index() {
$this->autoRender = false;
return new CakeResponse(array('body' => json_encode($this->User->find('all'))));
}
(2) AppController i did this:
var $components = array('RequestHandler');
function beforeFilter() {
if ( $this->RequestHandler->isAjax() ) {
Configure::write ( 'debug', 0 );
}
}
(3) I created separate html file which is not in cakePHP folder to test json response:
<body>
<a href="">jQuery</a>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "get",
url: "http://localhost/jungle/users",
success: function(response){
alert(response);
}
});
});
</script>
</body>
I am not getting any response from the cakephp backend when i open the html file mentioned in (3). I tried using the firebug and there were no response shown too.
However, when i tried accessing the cakephp users index page from my browser, the json is displayed out nicely:
[{"User":{"id":"1","name":"John","mobile_code":"+65","mobile number":"901111234"}}]
Could someone help me?
There is nothing wrong with your setup. I know this sounds silly, but have you included jQuery properly in your test HTML and is it successfully firing off the request?
Another thing to verify is where are you hosting your test HTML file? Is it being served from the webserver or is it just sitting on your desktop? If it is not being served, there is a good chance that javascript is disabled and not running.
As an aside,
isAjaxis deprecated in CakePHP 2. Instead, usethis->request->is( 'ajax' )to test for Ajax. This should not affect your problem though.