JTC
JTC

Reputation: 3464

validating form before it submit

WHAT IM DOING
I'm using jquery to validate form before it is send to server.
I'm validating every input, and if any of them return false i call event.preventDefault() and show the errors.(if it returns true I do nothing...)

THE PROBLEM
It was working fine, the script always run before the form send itself, but now I'm validating email, using ajax - checking if email isnt already in db or if the domain exists... but when the ajax starts, the the form wont wait until its finished and sends itself before the ajax finish and the input validates.

SOME SOLUTIONS MAYBE
I could call event.preventDefault() and after the validation is completed and it returns true I could try to undo the preventDefault perhabs by unbind and then submit through jquery submit the form again.

Or perhabs I could do onsubmit="checkInputs();" and it should wait until it returns true or false...

Solution - Adapted from the accepted answer by user Mirage

function validate(){
    $.ajax({
        url: 'http://google.nl',
        async: false,
        type: "POST",
        data: {test:'request'},
        success: function(data){
            console.log(data);
        }
    });    
    return data; // important
}

Upvotes: 0

Views: 139

Answers (3)

giorgio
giorgio

Reputation: 10212

Your script flow should be something like this:

  1. Bind onsubmit handler
  2. Send vars to server with ajax
  3. Check results
    1. When validates: remove handler and post form
    2. When false: show error messages and start over again.

And in code:

var handleValidationResponse = function(data) {
    if(data.errors != 0) {
        alert('Sorry my dear user, but you made a mistake');
        return false;
    }
    // aight, so it's all fine
    $('#myForm').off('submit').trigger('submit'); // unbind custom submit handler and post the form
};

$('#myForm').on('submit', function(e) {
    e.preventDefault();

    var $this = $(this);
    var serializedFormData = $this.serializeArray();
    $.post($this.attr('action'), serializedFormData, function(data) {
        handleValidationResponse(data);
    });
});

That should be it!

Upvotes: 0

user3759531
user3759531

Reputation: 99

you want:

onsubmit="checkInputs(); return false;"

Then you would grab the form e.g:

var frm = document.getElementById("myfrm");
frm.submit();

You would place the above in the else condition of your validation logic. Hope this helps.

Upvotes: 0

Mirage
Mirage

Reputation: 177

try to add

async: false

example:

$.ajax({
    url: 'http://google.nl',
    async: false,
    type: "POST",
    data: {test:'request'},
    success: function(data){
        console.log(data);
    }
});

Upvotes: 2

Related Questions