Reputation: 8507
I have a form of which I catch the submit event. I have to wait for a $.post
call in order to decide whether to submit it. I've tried this:
$('#my_form').submit(function(event){
var data = null;
$.post("/post/call").then(function(_data){
data = _data;
});
if ( $.isPlainObject(data) && data.status === 'ko' ) {
return false; // Do not submit the original form
} else {
// Submit the original form
}
});
But data
results to be always null
, also if _data
is valorized, because $.post
is an asynchrounous call. How can I wait for the $.post
call to be completed?
EDIT: As wrote in the comments, I would like to avoid $.ajax({async: true})
, because it freezes the page; is there any way to get the same effect without freezing the page?
Upvotes: 0
Views: 436
Reputation: 5004
If you are using MVC / C#, and can use a Json request to access your web service, know the following.
$.getJSON
Is asynchronous
SOLUTION: $.ajax
Can be set to synchronous
Upvotes: 0
Reputation: 190907
You should have some sort of flag that says the form is to be submitted or not as well as that the ajax is processing. Then when the ajax call passes, call $('#my_form').submit()
to send the form.
Loosely,
var validated = false;
$('#my_form').submit(function(event){
if (validated) {
return true;
}
$.post("/post/call").then(function(_data){
var data = _data;
if ( $.isPlainObject(data) && data.status === 'ko' ) {
// Do not submit the original form
} else {
validated = true;
$('#my_form').submit();
}
});
return false;
});
Upvotes: 2