Reputation: 3464
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
Reputation: 10212
Your script flow should be something like this:
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
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
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