I'm new to cakePHP but am close to quitting using it due to my inability of getting jQuery to work with it.
I'm using cakePHP 1.3 and so thought the Html and Js helpers had made Javascript and Ajax redundant but I can't really find any help/api documentation on how to use Js that is sufficient.
All I'm trying to do first of all is send some data to cakePHP with jQuery and then get some data back into jQuery and alert() it. For some reason this just isn't working. Here is my code:
test.js
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '/activities/add_activity',
data: 'type=social',
dataType: 'json',
success: function(data)
{
alert(data);
},
error: function()
{
alert('wut');
}
});
});
activities_controller.php
function add_activity()
{
if($this->RequestHandler->isAjax())
{
$this->autoRender = false;
$this->autoLayout = false;
$this->header('Content-Type: application/json');
echo json_encode(array('result'=>'hello');
return;
}
}
Every time I click the button with class='social' I get the alert "wut" which means error.
I have the RequestHandler component and Javascript, Js, and Ajax helpers included in my activities_controller.php.
Also, test.js and jquery.js is linked using html->script(); in default.ctp and all other jQuery stuff is working so it's not that.
I've also got this in my beforeFilter() for activities_controller.php:
if($this->RequestHandler->isAjax())
{
Configure::write('debug',0);
}
parent::beforeFilter();
Any ideas what is wrong? Is it a jQuery thing or a cakePHP thing? Or both?
Thanks in advance,
Infinitifizz
P.S.
I have never done AJAX in jQuery before so maybe it is something to do with that that is messing up, I've only ever done simple javascript AJAX.
Don't give up on CakePHP. There is a learning curve, but it's worth it.
I would specify the url like this:
<?php $Url = Router::url(array('controller'=>'activities','action'=>'addActivity'),true); ?>
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '<?php echo $Url ?>';
...
On the CakePHP side, my method would be like this:
function addActivity()
{
$this->autoRender = false;
$this->autoLayout = false;
App::import('Helper', 'Javascript');
$javascript = new JavascriptHelper();
echo($javascript->object(array('result'=>'hello')));
exit(1);
}
I never use if($this->RequestHandler->isAjax())
although I'm sure some kind soul will tell me why I should.
I prefer to camelCase method names in line with CakePHP convention.
Note that this line in your code: echo json_encode(array('result'=>'hello');
is missing a closing bracket.
Also, I wouldn't use jQuery to do simple AJAX like this - it can make it difficult to debug, but that's just personal preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With