CakePHP: Controller Response for Ajax Request is wrong
I'm using jQuery to make an AJAX request to some controller action. This request is activated from a button in the view of the edit action in the same controller.
My problem: The Ajax Request is returning all the code of the edit view (with all the forms and inputs) instead of the expected number. If I put the same ajax button in the view of the add action, it works perfect (it returns the number).
The edit and add actions remains as generated by default (with bake).
This is the jQuery function to make the ajax request
$.ajax({
type: 'POST',
url: 'checkTargets',
data: {target: tgt_array, channel: channel_type},
success:function(data){
$('#num_subscribers > span').html(data);
},
error:function(){
$('#num_subscribers > span').html("The subscribers could not be loaded");
},
timeout: 5000
});
}
This is the action
function checkTargets() {
if ($this->RequestHandler->isAjax()) {
if(!empty($this->params['form'])) {
$data = $this->params['form'];
if ($data['channel'] === 'SMS') {
$channel = 'sms';
} else {
$channel = 'pin';
}
$targets = $this->processPostTargets($data['target']);
$this->RequestHandler->respondAs('text');
//This echo a NUMBER
echo ClassRegistry::init('Selection')->countSubscribersInTarget($channel, $targets);
Configure:: write('debug', 0);
$this->autoRender = false;
exit();
}
}
}
Why is this ha开发者_JAVA技巧ppening?
Thanks
Just a suggestion without having access to everything, have you tried this?
$this->autoRender = false;
$this->layout = 'ajax';
Also I'd suggest keeping it simple:
$.post("/controller/checkTargets", function(data) {
alert(data);
}
function checkTargets() {
$this->autoRender = false;
$this->layout = 'ajax';
echo "Im working";
}
and go from there.
I fixed the problem. It was the URL param in the .ajax function (a noob mistake)
It should be a complete path to the referenced action in the controller.
This question helped me to understand the problem: best practice to use action url while calling ajax in cakePHP
Fixed Ajax Request:
$.ajax({
type: 'POST',
url: '/myapp/campaigns/checkTargets',
data: {target: tgt_array, channel: channel_type},
success:function(data){
$('#num_subscribers > span').html(data);
},
error:function(){
$('#num_subscribers > span').html("The subscribers could not be loaded");
},
timeout: 5000
});
thanks and excuse my english
精彩评论