FormのデータをaxiosやjQuery.ajaxで送信する
問題
画面上のHTMLのformの内容をajaxで送信したいです。
答え
axiosやjQuery.ajaxは送信するデータにFormDataを渡してやるとフォームの内容を送信してくれる。
ファイルも送信できる。
例)
<form>
<div><input type="text" name="sei" value=""></div>
<div><input type="text" name="mei" value=""></div>
<div><input type="radio" name="nenrei" value="10">10代</div>
<div><input type="radio" name="nenrei" value="20">20代</div>
<div><input type="radio" name="nenrei" value="30">30代</div>
<div><input type="checkbox" name="ok" value="チェック">テスト</div>
<div><input type="file" name="tenpu"></div>
<div><button type="button" onclick="soshin()">ajaxで送信する</button></div>
</form>
<pre></pre>
<script>
function soshin() {
let fd = new FormData($('form').get(0))
$.ajax({
url:'test.php',
type:'post',
data: fd,
processData: false, // dataをクエリ文字列にしない
contentType: false // jQueryデフォルトの application/x-www-form-urlencoded をセットさせない
}).done(function(data) {
// OK
$('pre').text(data)
}).fail(function() {
// NG
})
}
</script>
結果

axiosも同様に可能。
<script>
function soshin() {
let fd = new FormData(document.querySelector('form'))
axios.post('test.php', fd)
.then(function(response) {
// OK
console.log(response)
document.querySelector('pre').textContent = response.data
}).catch(function(error) {
// NG
console.log(error)
})
}
</script>
送信するフォームは、HTMLに存在するformに限らず、FormDataを手作りしてもよい。
const data = new FormData();
data.append("mail", "test@example.com");
data.append("name", "hogefuga");