Mike Arrh Mike Arrh -5 years ago 122
Ajax Question

Choosing order of events, so that onchange events fire before a submit

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download