views:

154

answers:

4

Hi,

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.

+3  A: 

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.

Leo
+1  A: 

This probably is offtopic, but...

What I do in order to have the application's root in my javascript:

In the /app/views/layout/default.ctp I have following code

<?php
echo $javascript->codeBlock("var root = '".$html->url('/')."';");
?>

Your parameter url will look like:

url: root+'activities/add_activity',

this way even if you app is in a subfolder or in a tld domain the script will work properly.

Returning "wut" for me means that the script couldn't reach the page in your url parameter. Especially if you working in a subdirectory it will look in http://server.com/activities/add_activity. I am 99% sure that this is the problem :)

Another suggestion: Remove Ajax while it was meant to work with Prototype rather with jQuery

Nik
Ah! Thanks! Sorry for the late reply everyone, I've been away for the last week, but thanks Nik I'm at least getting there because of this! It now calls the function after I added that line to default.ctp but I always get back 'wut' though so that means at least the jQuery is running but always getting the error...any tips on what to do next?
Infiniti Fizz
Oh, nearly forgot, I also changed the add_activity function to use $this->javascript... like Leo said before so maybe that's helped too.
Infiniti Fizz
Ah, just used firebug and it seems that cakephp is sending back an error that seems to contain "Warning: DbAcl::check() - Failed ARO/ACO node lookup in permissions check. Node references" and then it shows the User array with the logged in users' record from the users table. So I think it was an ACL problem, I've now added add_activity() to the allow() permissions and so now I get success back from the jQuery! But...alert(data) just gives me "[object Object]" is this because the response isn't json? I'm very new to JSON and only tried it because it was in a tutorial...
Infiniti Fizz
Yay works now! Sorry as I hadn't used JSON before I didn't know how to access the data, doing alert(data.result) returned 'hello' which is what it should do :D now my next step is to get cakePHP to understand the additional data "data: 'type=social'" and so work out the 'social' button was pressed...Thanks everyone for the help btw, I couldn't have done it without you :)
Infiniti Fizz
Whey! Just sorted that 2nd problem too using this tutorial where he passes values from jQuery to cakephp: http://nuts-and-bolts-of-cakephp.com/2009/01/21/jquery-in-the-cakephp-world-part-2-is-client-side-code-all-that-great/
Infiniti Fizz
+2  A: 

I hate the Ajax Helper in CakePHP... that is until I found this: http://blog.loadsys.com/2009/05/01/cakephp-jquery-ajax-helper-easy-scriptaculous-replacement/

Now I can use native CakePHP Ajax calls with jQuery! Look into this. I was able to solve all of my "simple" ajax issues with this darg-n-drop ajax helper replacements. I just drop this into the helpers directory in my app and replace the ajax.php that is there and viola! jQuery is working. You need to include the jQuery script in the layout of course. Try it, you will love CakePHP again!

cdburgess
+1  A: 

I would recommend you to use CakePHP json layout to output the data from view instead of echo json data from your controller.

The-Di-Lab