Skip to content
loading...

re: Async Form Posts With a Couple Lines of Vanilla JavaScript VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Honestly, I haven’t gotten around to using it enough for me to feel comfortable advising others to use it. I wonder if the prevent default call wo...
 

You could use an II(AA)FE to use async-await:

document.addEventListener('submit', e => {
  const form = e.target;
  const statusBusy = form.querySelector('.status-busy');
  const statusFailure = form.querySelector('.status-failure');

  (async () => {
    const res = await fetch(form.action, {
      method: form.method,
      body: new FormData(form)
    })
    const doc = new DOMParser().parseFromString(await res.text(), 'text/html')

    const result = document.createElement('div');
    result.innerHTML = doc.body.innerHTML;
    result.tabIndex = -1;
    form.parentNode.replaceChild(result, form);
    result.focus();
  })().catch(err => {
    Array.from(form.elements).forEach(field => field.disabled = false);
    lastActive.focus();

    statusBusy.hidden = false;
    statusFailure.hidden = false;
  });

  // ...

});
code of conduct - report abuse