Delmon Young
Delmon Young

Reputation: 2053

jQuery validation conflicting with AJAX call

I've got a form with a pretty simple validation snippet as well as a simple AJAX call, except when I try to put the two together I'm running into problems. If I put the validation snippet ahead of the AJAX call the validation works but the AJAX call simply does not submit. If I put the AJAX call ahead of the validation the AJAX call works and the validation doesn't. I'm really lost and been banging my head for hours over this one. Any help is greatly appreciated!

$("#headerForm").submit(function(){

    var validate = true;      
    $("#headerForm :input").each(function(){                   
        var $this = $(this);                           
        if(this.id == "phoneNumber" && $this.val().length < 10 ){     
            alert("Please enter a valid phone number");
            validate = false;
            return false;        
        } else if(!this.value.length){           
            alert("field is required");
            validate = false;
            return false;  
        }           
    });
    return validate;

var name = $("#name").val();
    var phone = $("#phone").val();

    var dataString = 'name='+ name + '&phone=' + phone; 

    $.ajax({  
      type: "POST",  
      url: "/bin/headerForm",  
      data: dataString,  
      success: function() {  
        $('#headerForm').html("<div id='message'>Thank you</div>");  
      }  
    });  
    return false; 
 });

Upvotes: 0

Views: 201

Answers (1)

Kerem
Kerem

Reputation: 317

The best practice would be to move validation code into a function, then call it in submit handler:

function validateForm() {
    var validate = true;
    $("#headerForm :input").each(function () {
        var $this = $(this);
        if (this.id == "phoneNumber" && $this.val().length < 10) {
            alert("Please enter a valid phone number");
            validate = false;
            return false;
        } else if (!this.value.length) {
            alert("field is required");
            validate = false;
            return false;
        }
    });
    return validate;
}

Then the submit handler:

$("#headerForm").submit(function () {

    if (validateForm()) {
        var name = $("#name").val();
        var phone = $("#phone").val();

        var dataString = 'name=' + name + '&phone=' + phone;

        $.ajax({
            type: "POST",
            url: "/bin/headerForm",
            data: dataString,
            success: function () {
                $('#headerForm').html("<div id='message'>Thank you</div>");
            }
        });
    }
    return false;
});

Upvotes: 2

Related Questions