0

I have a js code where it is validating a form using jquery validations. and after that it is calling ajax.

$('.form').validate({
    rules: {
        ---- 
    }
});
$('#submit').click(function() {

    $.ajax(url,{
        data:data,
        success:onSuccess,
        error:onError,
        type:POST
    });
    return FALSE;
});

onSuccess and onError are simple functions. url is predefined

But with this code its not entering into validations and directly calling ajax whatever might be the case.

Smile
  • 2,770
  • 4
  • 35
  • 57
madhu
  • 27
  • 1
  • 6

4 Answers4

4

You should not bind a click event on submit button. You should place your function on submitHandler option of JQuery validation. Like this

 $('.form').validate({
    rules: {
    ---- 
    },
    submitHandler: function(form){
        //your code here..
    }
});

Here's the JQuery Validation docs to better understand.

nix
  • 3,262
  • 2
  • 21
  • 36
0

Try this:

$(".form").submit(function(e) {
    e.preventDefault();
}).validate({
    rules: {...},
    submitHandler: function(form) { 
        alert("Do some stuff...");
        $.ajax(url,{
           data:data,
           success:onSuccess,
           error:onError,
           type:POST
        });
        return false;  
    }
});

Read Preventing a form from submitting in jQuery Validate plugin's submitHandler function

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Use the submit handler to handle custom submit logic

$('.form').validate({
    rules: {

    },
    submitHandler: function() {
        //your ajax save
        $.ajax(url, {
            data:data,
            success:onSuccess,
            error:onError,
            type:POST
        });
        return false;
    }
});

If you want to use a custom submit logic, then check whether the form is valid like

$('#submit').click(function() {
    if(!$('.form').valid()){
        return false;
    }

    $.ajax(url,{
        data:data,
        success:onSuccess,
        error:onError,
        type:POST
    });
    return false;
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Recheck your form class better to use id for form

 $(".form").validate({

After Validation check better to use submitHandler function which will call ajax like:

 submitHandler: function(form) {
                    form.submit();
                }