views:

97

answers:

3

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)) {
        $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."

+1  A: 

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?

Rob Wilkerson
+1  A: 

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/persistant.

cdburgess
If you use other caching engines, clear_cache plugin is worth installing. It provides you with a shell (called via cake clear_cache) and cleans the tmp folder as well as other tmp stuff. Kind regards
benjamin
Thanks CD, your suggestion with changing the submit to the button worked.. The submit was actually submitting the form. Careless mistake on my part.
wcolbert
You're welcome. Glad to help.
cdburgess
A: 

Hello wcolbert,

what happens if you render the page, which you would like to see in the case of no redirect?

What happens if you insert an alert like 2?

function(e){
  alert("clicked!!"); <--- 2
  e.preventDefault(); <--- 1
  $.ajax({...

Maybe line 1, becomes interesting later. Kind regards

benjamin