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

89
March 18, 2022, at 2:40 PM

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 1

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()
}
Rent Charter Buses Company
READ ALSO
Woocommerce cart page custom js not working after applying coupon. I send cart data to external domain on proceed to checkout

Woocommerce cart page custom js not working after applying coupon. I send cart data to external domain on proceed to checkout

I am sending the cart data of woocommerce to an externally hosted checkout page with the click of the 'proceed to checkout buttonI just create inputs by looping the table and changing the cart form action URL to my external checkout page URL

143
Firefox treating pasted image from clipboard as a string instead of file

Firefox treating pasted image from clipboard as a string instead of file

I am trying to get image from on paste event from a contenteditable divIt is working fine in chrome but isn't working in firefox

129
Run search function on each keypress

Run search function on each keypress

I have this function that when I click on submit or press Enter that uses the value in the input and scans for it in the child of each div, and if it finds one it hides all and shows only that div

117
How to save custom color on localStorage jquery?

How to save custom color on localStorage jquery?

I` have a function in jquery witch allow users to change background color of siteBut if they refresh the page background-color go to default

131