2.

Form submission canceled because the form is not connected

編集
この記事の要点
  • Form submission canceled because the form is not connectedJavaScript で動的に削除された form を submit した警告
  • 原因 ①: フォーム要素が DOM から削除された後に form.submit()
  • 原因 ②: フォームの action が空文字 / 不正
  • 原因 ③: SPA で route 切替時にフォームが消えた
  • 対処: フォームが DOM に存在することを確認してから submit

 

エラーの状況

# Chrome の警告
Form submission canceled because the form is not connected.

# 動作: フォーム送信が実行されない
# サーバへリクエストが行かない

原因と対処

原因 1: form が DOM から削除されている

# 修正: 削除前に送信 form.submit(); form.remove(); // 送信後に削除

原因 2: appendChild する前の動的フォーム

// 動的フォームをまだ append していない
const form = document.createElement("form");
form.action = "/api/submit";
form.method = "POST";

const input = document.createElement("input");
input.name = "token";
input.value = "abc123";
form.appendChild(input);

form.submit();
// → Form is not connected (まだ DOM に追加されていない)

// 修正: body に追加してから submit
document.body.appendChild(form);
form.submit();

// 一般的なパターン: 自動送信
const autoSubmit = () => {
    const form = document.createElement("form");
    form.action = "/payment/external";
    form.method = "POST";

    const fields = { token: "abc", amount: 1000 };
    for (const [key, value] of Object.entries(fields)) {
        const input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = value;
        form.appendChild(input);
    }

    document.body.appendChild(form);  // ← 必須
    form.submit();
};

原因 3: action 属性が空 / 不正


原因 4: SPA でフォーム要素が remove された

// React / Vue 等で
function MyForm() {
    const [show, setShow] = useState(true);
    return show ? (
        ...
    ) : null;
}

// onSubmit ハンドラ内で setShow(false) すると DOM から消える
// その後 e.target.submit() するとエラー

イベントハンドラからの submit

// フォーム送信前にチェック
document.getElementById("myForm").addEventListener("submit", (e) => {
    e.preventDefault();

    // バリデーション
    if (!validate()) {
        return;
    }

    // データ加工
    const data = new FormData(e.target);
    data.append("timestamp", Date.now());

    // submit (e.target がまだ DOM にある)
    e.target.submit();

    // ❌ こうすると問題:
    // e.target.remove();  // ← submit より前に削除
});

fetch / Ajax 推奨

動的フォーム送信なら form.submit() よりも fetch / XHR が制御しやすい:

// fetch でフォームデータ送信
document.getElementById("myForm").addEventListener("submit", async (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);
    try {
        const response = await fetch(e.target.action, {
            method: e.target.method || "POST",
            body: formData,
        });
        const result = await response.json();
        console.log(result);
    } catch (error) {
        console.error("送信失敗:", error);
    }
});

# メリット:
# - フォーム要素の状態に依存しない
# - レスポンスを受け取れる
# - エラーハンドリング可能
# - ページ遷移なし

外部サイト連携での自動送信パターン

// 決済プロバイダ等への自動 POST
function redirectToPayment(token, amount) {
    const form = document.createElement("form");
    form.action = "https://payment.example.com/checkout";
    form.method = "POST";
    form.style.display = "none";

    const fields = {
        token: token,
        amount: amount,
        return_url: location.origin + "/payment/return"
    };

    for (const [key, value] of Object.entries(fields)) {
        const input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = value;
        form.appendChild(input);
    }

    // body に追加してから submit
    document.body.appendChild(form);

    // submit の直前に form がまだ DOM にあることを確認
    if (form.isConnected) {
        form.submit();
    } else {
        console.error("フォームが DOM から消えた");
    }
}

関連: form 要素のチェック

// form.isConnected (DOM に接続されているか、ES6+)
const form = document.getElementById("myForm");
if (form && form.isConnected) {
    form.submit();
}

// 古い書き方
if (form && document.body.contains(form)) {
    form.submit();
}

// document.contains で確認
if (form && document.contains(form)) {
    form.submit();
}

関連エラー

  • Form submission canceled because the form is not connected: このページ
  • Failed to construct \'URL\': action 属性が不正な URL
  • CORS error: 別オリジンへの送信
  • Mixed Content: HTTPS ページから HTTP の form action

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. Uncaught TypeError: Illegal invocation
  2. Form submission canceled because the form is not connected
  3. Uncaught TypeError: location.href is not a function
  4. Access to XMLHttpRequest at 'url1' from origin 'url2' has been blocked
  5. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')