0

If I'm sending data from an anchor attribute:

<a id="123">foo</a>

With no <form> around it,

Using jquery's $.post() to one of my controllers:

    $('.add-fav').click(function() {
    var id = $(this).attr('id');
    $.post('/ajax/addFavorite', function(data){
    id : id
    }, 'json');
});

How can I retrieve the data within that controller? I'm not using a model to validate anything, so using Cake's built-in formhelper convention shouldn't matter.

     public function addFavorite() {
       $this->autoRender = false;

       $bar = $_POST['id'] // normally I'd do this to get '123' from the anchor id, but it doesn't work since it wasn't submitted within a form

        $dataBack = json_encode($bar);

       if($this->RequestHandler->isAjax()) {
            if($this->Session->read('Auth.User')) {
                return $dataBack;
            }
       }
 }

I can send a json_encoded associative array as data back to $.post(), but I can't seem to send what was originally sent back (e.g. id which goes through the controller and sending it back). Am I missing something fundamental here or is it not possible to do without sending the data in an input field (hidden maybe) inside of a <form>?

2 Answers 2

2

data to be passed id send as the second argument of $.post

 $('.add-fav').click(function() {
    var id = $(this).attr('id');
    $.post('/ajax/addFavorite',{id:id}, function(data){
   console.log(data);
    }, 'json');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Now I know why I like sticking to $.ajax(), since I actually remember how to properly structure it. Thanks!
0

Well there is a pretty good way to do it with CakePHP JS Helper too.

    $this->Js->get('.add-fav')->event('click',
        $this->Js->request(
        array(‘controller’ => ‘ajax’, ‘action' => 'addFavorite'),
           array(
               'data' => 'event.target.id',
               'async' => true,    
               'dataExpression' => true,
               'method' => 'POST',
               //'update' => '#element_id', // to paste the answer of the call
               //'before' => 'alert("Before request")',
               //'complete' => 'alert("Callback when request completed")',
               //'error' => 'alert("Callback for request error")',
               //'success' => 'alert("Success")', //code to execute if success
           )
        )
    );
    echo $this->Js->writeBuffer();

Comments

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.