I have created a form. On the submission of the form i make an ajax request which tells me whether the data is valid or not. What i want to do is that if the ajax response tells that the data is valid then it should submit the form but if data is not valid then it should not submit the form.
$('#agentLogin').submit(function(ev){
ev.preventDefault();
var username=$('#agentEmail').val();
var password=$('#agentPassword').val();
$.ajax({
url: '<?php echo $this->createAbsoluteUrl('site/agentLogin'); ?>',
type: 'POST',
data: {
email: username,
pwd: password
},
success: function(data){
if(data === 'invalid'){
$('#agentLoginStatus').html('Invalid Username and password');
}else if(data === 'deactivated'){
$('#agentLoginStatus').html('Account is deactivated');
}else if(data === 'valid'){
// submit form here
}
}
});
});
Problem:- When the data is not valid It does not submit the form. but if the data is valid then also it does not submits the form. How can i resolve this issue?
Already tried:-
$(this).submit();
return true;
Here we can use submithandler of the ajax. The reason is that the submithandler works with submit button and validates the data too..
Try this approach:
The reason it didn't work with your original code is that when you try to call
$(this).submit()
it triggers the same event handler which attempts to validate with AJAX request all over again and never actually submit a form. To fix it you need to tell event handler somehow that when you submit a form manually you don't want to run validation anymore. I am passing additional parameter for this:You can continue submission of a
<form>
with the native.submit()
method, which should only start the default action that was previously prevented without rerunning event bindings.Though, you'll also need to store a reference to the
<form>
asthis
can and will often be different betweenfunction
s, including embedded callbacks.