Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best practices writing JavaScript that uses AJAX call to decide if default action should be prevented

I’m using JavaScript and jQuery to write a handler for my form being submitted. Based on certain conditions, the handler may allow or prevent the form from submitting.

This is straight forward but is made more complex by the fact that the handler needs to make an AJAX call.

The issue is that my handler will return right away with true or false, but I won’t get the response from the AJAX call until later. But I need the result from the AJAX call to decide what the return value should be.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Seems like this must surely be a common scenario. Are there best practices for handling this case?

>Solution :

My answer on basis what was discussed shortly in the comments, there are (at least) two possible solutions.

  1. Async/await:

Wait for the ajax call to finish and prevent default behavior based on the response. (await $.ajax / await $.post/get)

  1. Prevent by default (as mentioned by @freedomn-m)

You could prevent the default behavior always, wait for the ajax call to finish and execute the desired behavior afterwards. For example with withholding a form submit.

e.preventDefault();
$ajax...
...
...
if (should_not_be_prevented) {
  $("#myForm").submit()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading