0

I have a form with various fields, some of which have onchange or onblur ajax methods. Sometimes those methods update other fields in the form. So, for instance, when you change a field for Mean or Standard Deviation, other fields for Upper Limit and Lower Limit would be automatically updated. This may require a trip to the server, depending on how the limits are calculated.

The trouble is, the user can click on a Submit button right after making one of these changes, and in that case the onchange and submit events are both triggered by the click. Then there's a race between the ajax method updating the fields that should be changed, and the Submit which might submit the old values of the fields.

How do I make sure that the Submit always fires after the onchange methods are done? Thanks.

Mike Arrh
  • 145
  • 9

2 Answers2

1

You keep track of whether you have an outstanding ajax request and, if you do, you prevent the default action of the submit event and instead set a flag that the user tried to submit the form. When the last outstanding ajax request is complete, if it's still appropriate to submit the form, you do that programmatically. If not, you tell the user why you didn't.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • How do you keep track of outstanding ajax requests? – Mike Arrh Jun 14 '16 at 18:00
  • @MikeArrh: Pretty much like you keep track of anything: With a variable. :-) For instance, you might have a variable that your central ajax functions close over that starts out at `0`. You increment it when you start an ajax call, and decrement it when you're done with one (success or error). A value > 0 means you have something in progress. – T.J. Crowder Jun 14 '16 at 18:02
  • Huh - I see that http://stackoverflow.com/questions/1822913/how-do-i-know-if-jquery-has-an-ajax-request-pending mentions that you can use $.active in jQuery to count the active ajax requests. That seems much safer to me than trying to keep track myself. – Mike Arrh Jun 14 '16 at 20:32
  • @MikeArrh: Keeping track isn't difficult, and `$.active` if [not documented](http://api.jquery.com/) (I've never heard of it). – T.J. Crowder Jun 15 '16 at 06:07
  • Thanks for your help! I'm checking this answer as okay, but keeping in mind the option of using $.active if it turns out to be reliable. – Mike Arrh Jun 15 '16 at 15:16
0

Just noting here the option of using $.active to count active ajax requests, see How do I know if jQuery has an Ajax request pending? Doesn't seem to be officially supported?

Community
  • 1
  • 1
Mike Arrh
  • 145
  • 9