13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptのFormDataは、ajaxで飛ばすまで中身を見ることができないっぽい。

Last updated at Posted at 2017-02-04

javascriptのメソッド、FormDataを使った時に
値が入らない???となって困ったのでシェアします。

結果的には入っていました

messages.js
  $('.message_form').on('submit', function(e) {
    e.preventDefault();
    var group_id = $('.group_id').val();

    var fd = new FormData($('.message_form').get(0))
    fd.append('body', $('.form').val())
    // $('.form').val() => "aaa"
    console.log(fd);
    // ここではfdを見ると FormData = {} となり、一見何も入っていないように見える
    $.ajax({
      type: 'POST',
      url: '/groups/' + group_id + '/messages.json',
      data: fd,
      processData: false,
      contentType: false,
      dataType: 'json'
    })
    .done(function(data) {
      console.log(data.body);
      // => "aaa"
      // なのに、ここで見るとfd.appendの部分で入れたbodyを見ることができる。
      data.name = $('.current_user_name').val();
      $('div.right__content').append(build_message(data));
      textField.val('');
    })
    .fail(function(data) {
      alert('送信に失敗しました。');
    });
  });
13
12
6

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
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?