Reputation: 946
I am trying to call a function in my application using ajax. The problem is that I don't want the function to call in the beforeFilter function of cakephp.
$.ajax({
dataType: 'json',
url: '/users/add/'+id,
success: function(data){
}
});
public function add($id = NULL)
{
echo "test";
die;
}
Whenever I use the ajax call, cakephp loads the beforeFilter function.
Is there a way to bypass the beforeFilter function?
Thanks.
Upvotes: 2
Views: 2137
Reputation: 4866
CakePHP's 'Request Life-cycle callbacks' are a very handy thing. They are there so that you don't have to implement such logic for every controller and are also an integrant part of CakePHP's MVC paradigm. Look here for more info on Cake's wrappers for the Models, Views and Controllers.
You can completely remove this (or any) callback via the Controller's implementedEvents()
function but I strongly recommend not to do this.
@thaJeztah 's solution is one of the two possible.
But why do you need to bypass beforeFilter()
? Is there a very strong thing that pushes you to do this?
You can also skip all ajax requests in the beforeFilter()
with something like:
public function beforeFilter()
{
if ( !$this->request->is('ajax')) {
//Do whatever
}
}
but really do you need this? What is obstructing you there? Maybe you're using this callback method incorrectly?
Also keep in mind that hte parent controller's beforeFilter()
will also be called if explicitly called in the child via parent::beforeFilter()
and if there is something there the request will also go through there.
Upvotes: 2
Reputation: 29077
Just check if the current request is made via AJAX inside your beforeFilter;
public function beforeFilter()
{
if ($this->request->is('ajax')) {
return;
}
// rest of your code
}
This will not disable the beforeFilter() of components attached to your controller
Upvotes: 0
Reputation: 11853
A better way to implement what you're trying to do is this:
function beforeFilter() {
if (in_array($this->action, array('list', 'protected', 'actions',
'here')) {
// Do your authentication
}
}
Upvotes: 2