Modal form with AJAX save

Submit without leaving the page, then close the modal.

Bootstrap · Modal form with AJAX saveIntermediate
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addTitle" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" id="addForm">
      <div class="modal-header">
        <h5 class="modal-title" id="addTitle">Add item</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <label for="itemName" class="form-label">Name</label>
        <input type="text" class="form-control" id="itemName" name="name" required>
        <div class="text-danger small mt-2" id="addError"></div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary" id="addBtn">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
  document.getElementById('addForm').addEventListener('submit', async function (e) {
    e.preventDefault();
    var btn = document.getElementById('addBtn');
    btn.disabled = true;
    try {
      var res = await fetch('/api/items', { method: 'POST', body: new FormData(this) });
      if (!res.ok) throw new Error();
      bootstrap.Modal.getOrCreateInstance(document.getElementById('addModal')).hide();
      this.reset();
    } catch (err) {
      document.getElementById('addError').textContent = 'Could not save. Try again.';
    } finally { btn.disabled = false; }
  });
</script>
modalformfetchspinner