0
0

More than 1 year has passed since last update.

FormDataオブジェクトにデータをappendしてAjaxでpostする

Posted at

サーバー側にpostする値を加工する必要があったので
フォームに対して少し手を加えた。

data = new FormData($("id"))

let hoge = '';
data.append('fuge', hoge)

$.ajax({
    data: data,
    type: "POST",
    dataType: "json",
    url: "url"
})
.done(function(data, textStatus, jqXHR) {
    console.log('success')
})
.fail(function(jqXHR, textStatus, errorThrown) {
    console.log('fail')
});

送信実行結果

Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.

どうやらnew FormDataで渡しているセレクタに対して.get(0)が必要みたい。

data = new FormData($("id").get(0))

追記して再度送信実行。

Uncaught TypeError: Illegal invocation

ファッ?!
調べたらどうやらAjaxにオプションを追加したらいけるとのこと。
ajax - Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation" - Stack Overflow
オプション追記して送信成功した。

data = new FormData($("id").get(0))

let hoge = '';
data.append('fuge', hoge)

$.ajax({
    data: data,
    processData: false,
    contentType: false,
    type: "POST",
    dataType: "json",
    url: "url"
})
.done(function(data, textStatus, jqXHR) {
    console.log('success')
})
.fail(function(jqXHR, textStatus, errorThrown) {
    console.log('fail')
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0