guest
guest

Reputation: 2224

cannot prevent default on form ajax submit

I am not able form from going to the Post URL after clicking submit. How can I debug this? I could see very quickly there's an error on console.log right before the form opens the submit URL, but I could not preventDefault the form submission to see what error is...

$('#done').click(function(e){
        var failed = 0;

        formData=$("form").serializeArray();        
        for(var i=0; i<formData.length;i++){
            console.log(i+': ' +formData[i].value);
            if(formData[i].value=="") {
                failed =1;
            } 
        }

        if(failed){
            console.log('failed');

        } else {
            console.log('success');
            var loginFormURL = form.find('form').attr("action");
            //return false;
            $.ajax({
                url : loginFormURL, //need to tell which URL to submit to
                type: "POST",
                data : formData, //serialized data
                success:function() {
                    console.log("succeeded"); 
                    return false;
                },
                error: function() {
                    console.log("failed");
                    return false;
                }
            });
            return false;
        }


    });

Upvotes: 1

Views: 344

Answers (1)

mamdouh alramadan
mamdouh alramadan

Reputation: 8528

what you are trying to do is to set return false inside your else condition:

else{
//some code
          return false;
                }
            });
            return false;
}

however, what you should be doing is to prevent the click at all using e.preventDefault() as:

$('#done').click(function(e){
        e.preventDefault();
        var failed = 0;
        formData=$("form").serializeArray();    
        //rest of the code here

Or, you can return false at the end of the function like so;

$('#done').click(function(e){
        var failed = 0;

        formData=$("form").serializeArray();        
        for(var i=0; i<formData.length;i++){
            console.log(i+': ' +formData[i].value);
            if(formData[i].value=="") {
                failed =1;
            } 
        }

        if(failed){
            console.log('failed');

        } else {
            console.log('success');
            var loginFormURL = form.find('form').attr("action");
            //return false;
            $.ajax({
                url : loginFormURL, //need to tell which URL to submit to
                type: "POST",
                data : formData, //serialized data
                success:function() {
                    console.log("succeeded"); 
                    return false;
                },
                error: function() {
                    console.log("failed");
                    return false;
                }
            });
        }
  return false; //<------ it goes here
}

Upvotes: 1

Related Questions