This is killing me. I'm using JQuery 1.10.2 and Cakephp 2.2 and I want to do a GET from javascript. This is my code:
Javascript:
var arg='/sites/fechas/10-02-2013';
$.get(arg, function(data) {
console.log(":" + data);
});
CakePHP code (SitesController.php):
public function fechas($fecha_reserva) {
$this->autoRender = false;
$fechas = $this->Informacion->find('count', array(
'conditions' => array(
'Informacion.fechas' => str_replace('-', '/', $fecha_reserva))
));
return json_encode($fechas);
}
From chrome developer tools
Request URL:http://my.web.com/sites/fechas/10-02-2013
Request Headers view parsed
GET http://my.web.com/sites/fechas/10-02-2013 HTTP/1.1
Accept: */*
Referer: http://my.web.com/reserva
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36
If I write the url in the browser I get a response (just a number). But from javascript I get nothing.
Use a view. Don't return directly from the Controller. You can either:
The data views approach is very good however you will need todo some setup as described in the link - parseExtensions, add the RequestHandlerComponent, etc. It is cleaner than the second option. Check the documentation and decide which one is for you. The second option is the "old way to do it". Anyway if you want to do it the by the second way this is what you need to do:
ajax.ctp
layout file under View/Layouts
. Can be called whatever you likecontent_for_layout
display in it: <?php echo $content_for_layout; ?>
<?php echo json_encode($fechas);?>
RequestHandler
component if you are not getting the right headersIn your controller after you get the data:
$this->set('fetchas', $fechas);
$this->render('your_view's_name_here')