2

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');
    }

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

5 Comments

The data: { id: id, name: name } part takes care of the query parameters, I only have the parameters on the client, so I can't parse them with php
The data { id: id..} takes care of the data that will be posted. You're using 'post' as type for your AJAX request, and also expecting as POST inside your controller, however the URL you're posting to doesn't include id nor name
Ah ofcourse, instead of reading it from the querystring, I should be reading from $this->request->data
That's probably the most logic solution yes :)
How to post using just JS code? For the URL property in the Ajx function?
0

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];

Comments

-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();
                }
            }
        });
});

2 Comments

You may want to add some texts and explain what your code is doing. In that way, many people will receive benefit.
Seems like a blind copy-paste considering that it contained placeholder text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.