例1aを現代風に書き直したものです。新しいブラウザならこちらで大丈夫のはずです。
お名前:
まずは form をやめて簡単にしました。
<p>お名前:<input id="user"> <button type="button" onclick="doit()">送信</button></p> <div id="result"></div>
doit() では新しい fetch を使っています。
<script>
function doit() {
const u = encodeURIComponent(document.getElementById("user").value);
fetch("ex1.php",
{ method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: "user=" + u })
.then(response => response.text())
.then(data => document.getElementById("result").innerHTML = data);
}
</script>
form を生かすなら,
<form id="myform" onsubmit="doit();return false;"> <p>お名前:<input name="user"> <input type="submit" value="送信"></p> </form>
としておいて,
<script>
function doit() {
const form = new FormData(document.getElementById("myform"));
fetch("ex1.php", { method: "POST", body: form })
.then(response => response.text())
.then(data => document.getElementById("result").innerHTML = data);
}
</script>
のようにすれば form の内容が丸ごとサーバに送られます。