0

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?

asked Mar 7, 2012 at 15:18
7
  • possible duplicate of Synchronous calls with jquery Commented Mar 7, 2012 at 15:22
  • Why not just put what you want to wait to do at the end async callback? Commented Mar 7, 2012 at 15:24
  • where do you get then .then() from. a callback function gets attached in the post with a comma. your if must also be in the callback, because data is not set before the post is completed. Commented Mar 7, 2012 at 15:24
  • Use synchronous call as Felix Kling advised. Everything, available with $.post is as well available via $.ajax; Commented Mar 7, 2012 at 15:27
  • 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? Commented Mar 7, 2012 at 15:46

2 Answers 2

2

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;
});
answered Mar 7, 2012 at 15:21
Sign up to request clarification or add additional context in comments.

1 Comment

You probably should add another flag which indicates whether a call is in progress.
0

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

answered Mar 7, 2012 at 15:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.