开发者

Problem during AJAX Request to CakePHP Plugin

im working on a plugin which extend a basic cakePHP plattform. This plugin includes a controller, which will be called by a external ajax request with jQuery. The whole architecture is a Client-Server one. The Problem is, that if i send data to the controller of the plugin, the $this->data value is always empty. Have anyone an idea where is the Problem? Here is the code:

// client code
$('#upload').click(function() {

        // data for testing
        var media = {};
        media.name = 'R开发者_开发技巧ihanna - S and M';
        media.userid = 5;
        media.description = 'Song of Rihanna';
        media.rating = 4;
        media.comments = new Array();

        var comment = {};
        comment.id = 1;
        comment.user_id = 2;
        comment.text = 'good';
        media.comments.push(comment);

        var comment2 = {};
        comment2.id = 2;
        comment2.user_id = 3;
        comment2.text = 'nice';
        media.comments.push(comment2);


        var json = $.toJSON(media);

        $.ajax({
            url:'http://server.localhost/mediamanager/connectors/add',
            async: false,
            dataType: 'json',
            type:'POST',
            data:json,
            success:function(response) {
                console.log(response);
            },
            error:function(response, status, text) {
                console.log(response);
                console.log(status);
                console.log(text);
            }
        })

    });

Here is the cakephp code. Another thing is that the $this->RequestHandler->isAjax() always returns false thoug i make an ajax request.

// server code
function add()
{

    if ($this->RequestHandler->prefers() == 'json') {
            Configure:: write('debug', 0);
            $this->autoRender = false;
            $this->layout = 'ajax';
            if(empty($this->data)) {
                echo "data is empty";
            } else {        
                echo "data received";
            }   

    } 

}

I hope anybody can help, because this thing is driving me crazy.


You need to POST the data as 'data', with the current setup, you will find your postdata in $this->params['form'].

Alternatively you could submit the postdata straight to $this->data by amending the line in your ajax request:

data: {data: json}


May be you should try $this->params['isAjax'] == 1 instead of $this->RequestHandler->isAjax(), but remember to add "RequestHandler" component in the controller first. ;) use this to see what data your getting pr($this->params);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜