Reputation: 2269
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>
?
Upvotes: 0
Views: 5776
Reputation: 1266
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();
Upvotes: 0
Reputation: 31033
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');
});
Upvotes: 2