CakePHP cancel redirect to view after submitting ajax add action
I'm trying to submit a form via AJAX and prevent a redirect after the form is submitted. I don't understand why I'm having this issue since I set autoRender to false.
Controller Code
function add() {
$this->autoRender = false;
if (!empty($this->data开发者_C百科)) {
$this->data['Comment']['user_id'] = $this->Auth->user('id');
$this->Comment->create();
if ($this->Comment->save($this->data)) {
}
}
}
JS event handler
$(".submit_comment").live("submit",commentSubmitHandler);
function commentSubmitHandler(event){
$.ajax({
type: "post",
url: $("#webroot").val() + "comments/add",
data: data,
dataType: "json",
success: function(data){
alert("win");
},
error: function(data){
alert("fail");
}
});
return false;
}
The form data is submitted and saved just fine, but why the heck is it leaving the page? Also, it seems to be doing it before finishing the js because the alerts never actually go off. Therefore there is a definite redirect straight from the controller action "add."
Try adding a link to the submission js outside of the form to test if the submission works that way. If it does, then you may need to change the button from a type="submit" to a type="button". It could be that the "submit" button is actually submitting the form.
The alternative is to verify the <form>
tag is submitting through the js and not posting to the add function in the controller.
In addition, check to make sure nothing is being cached (just in case - I have seen it happen) by clearing out the cache files in tmp/cache/persistan
t.
Try to put $this->autoRender = false;
inside the if of save or in the final line...like
function add() {
if (!empty($this->data)) {
$this->data['Comment']['user_id'] = $this->Auth->user('id');
$this->Comment->create();
if ($this->Comment->save($this->data)) {
....
$this->autoRender = false;
}
}
}
I suspect that your form is submitting which makes me think that the return false
statement at the end of your event handler isn't doing what you think it's doing. Is the .submit_comment
element a form or a button?
精彩评论