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

Issue

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.

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()
}

Answered By – clash

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *