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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Best practices writing JavaScript that uses AJAX call to decide if default action should be prevented without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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()
}
We are here to answer your question about Best practices writing JavaScript that uses AJAX call to decide if default action should be prevented - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji