Mark
Mark

Reputation: 3271

Posting to controller with jquery ajax in CakePHP

I want to post data to a controller in CakePHP, but posting with JQuery always results in an error and I can't figure out why.

In my view I have the following method, that posts the data to the controller page

function RenameNode(name, id)
{
    $.ajax({
        type: "POST",
        url: '<?php echo Router::url(array('controller' => 'categories', 'action' => 'rename')); ?>',
        data: {
            id: id,
            name: name
        },
        success: function(){

        }
    });
}

My controller method looks like this:

public function rename($id = null, $name = null) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }

    if(!$id)
    {
        $id = @$this->request->query('id');
    }

    if(!$name)
    {
        $name = @$this->request->query('name');
    }           

    if (!$id) {
        throw new NotFoundException(__('No id'));
    }

    $category = $this->Category->findById($id);
    if (!$category) {
        throw new NotFoundException(__('Invalid category'));
    }

    $this->autoRender = false;
    $this->layout = 'ajax';

    if ($this->request->is('post') || $this->request->is('put')) {
        $this->Category->id = $id;
        $this->request->data['Category']['name'] = $name;


        if ($this->Category->save($this->request->data)) {
            $this->Session->setFlash(__('The category has been updated.'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('Unable to update the category.'));
        }
    }
}

When I do a post with the jquery method, I keep getting the following error message in my log:

2013-05-20 11:34:25 Error: [NotFoundException] No id
Request URL: /cakephp/categories/rename
Stack Trace:
#0 [internal function]: CategoriesController->rename()

When I comment the request checks for get and post, the controller itself works perfectly when I call it with /categories/rename?id=1&name=test. For some reason the ajax way doesn't work, but I can't figure out why. Any ideas?

Update

I fixed it by changing the following code, now it works perfectly

    if(!$id)
    {
        $id = @$this->request->query('id');
    }

    if(!$name)
    {
        $name = @$this->request->query('name');
    }

to

    if(!$id)
    {
        $id = @$this->request->data('id');
    }

    if(!$name)
    {
        $name = @$this->request->data('name');
    }

Upvotes: 2

Views: 17796

Answers (3)

Claudio Rivas
Claudio Rivas

Reputation: 1

$('a.ajax-delete-pdf').on('click', function (event) {
    event.preventDefault();
    var id = $(this).data('id');
    $.ajax(
        {
            url: webroot + 'productos/ajax_eliminar_pdf/' + id ,
            async : false,
            success: function(respuesta)
            {
                if(respuesta == 'Borrado')
                {
                    $(this).parent().toggle();
                }
            }
        });
});

Upvotes: -1

PPB
PPB

Reputation: 3087

use somthing like that

data = 'name='+name+'&id='id'';

$.ajax({

    type:'post', 

    url: '/categories/rename',

    data: data

});

and in controller function

$name=$_POST[name];

$id=$_POST[id];

Upvotes: 0

thaJeztah
thaJeztah

Reputation: 28987

You are not including the id and/or name in the URL you're posting to;

echo Router::url(array('controller' => 'categories', 'action' => 'rename'));

Will output;

/categories/rename

But you're expecting

/categories/rename/1/test

Or

/categories/rename?id=1&name=test

Change the URL in your AJAX code to something like;

echo Router::url(array(
   'controller' => 'categories',
   'action' => 'rename',
   0 => $this->request->params['pass'][0],
   1 => $this->request->params['pass'][1]
));

Which should output the right url, containing the original id and name of the current request (e.g. /categories/rename/123/oldname)

Upvotes: 4

Related Questions