🔄 Your AJAX Request Keeps Sending the Form Data From BEFORE the User’s Last Edit
A form submits via AJAX, and the server receives data that’s one step behind what the user actually typed – the previous value, not the current one – because the code reads the form’s values at the moment a request is BUILT, but that build happens on an event that fires before the browser has finished updating the field’s actual value for the keystroke or change that just occurred.
🔎 The Problem
let currentValue = '"'"''"'"';
input.addEventListener('"'"'keydown'"'"', function () {
currentValue = input.value; // <- reads the value BEFORE this
// keystroke is applied to the field
});
button.addEventListener('"'"'click'"'"', function () {
$.post('"'"'/api/save'"'"', { value: currentValue });
// Always one keystroke behind, because `keydown` fires before the
// browser updates `input.value` for the key that was just pressed -
// `currentValue` is perpetually capturing the PREVIOUS state.
});
✅ Fix: Read the Value at Send Time, From the Right Event
- Simplest fix: don’t cache the value on an intermediate event at all – read `input.value` directly inside the click handler, at the moment the request is actually built, which guarantees the most current value.
- If a running snapshot IS needed for other reasons, use the `input` event instead of `keydown`/`keyup` – `input` fires AFTER the field’s value has already been updated to reflect the change, which is the specific ordering guarantee `keydown` doesn’t provide.
⚠️ The General Pattern to Watch For
- Any time a value is captured on one event and used by a handler for a DIFFERENT, later event, the relative firing order of those two events (and whether the value has actually settled by the first one) becomes part of your program’s correctness – it’s worth checking explicitly rather than assuming intuition about event order.
- `keydown` → browser applies the key → `input` fires → `keyup` fires is the actual sequence for standard text input in modern browsers – `keydown` is reliably too early for reading the field’s post-keystroke value.
An event firing doesn’t mean the state you care about has already changed – it just means something happened, and the order of WHAT happened when is a detail worth checking, not assuming.
