Help us understand the problem. What is going on with this article?

非同期 メッセージ送信

More than 1 year has passed since last update.

スタート

1. ajaxでデータを飛ばす

  $("#new_message").on("submit", function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        var url = $(this).attr('action')
        $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                dataType: 'json',
                processData: false,
                contentType: false
            })

1. コントローラー起動
2. format.jsonで返す


  def create
    @message = @group.messages.new(message_params)
      if @message.save

        respond_to do |format|
           format.html {redirect_to group_messages_path(@group)}
           format.json
        end

      else
        @messages = @group.messages.includes(:user)
          flash.now[:alert] = 'メッセージを入力してください。'
          render :index
      end

  end


変換

コントローラーのアクション名と連動 (createjson.id @message.id
json.name @message.user.name
json.created_at @message.created_at.strftime('%Y/%m/%d %H:%M:%S')
json.content @message.content
json.image @message.image.url

1. doneで受ける
2. appendする

   .done(function(data) {
                var html = buildHTML(data);
                $(".main-message-container").append(html);
                $(".footer-box__text-field").val('')
                $(".upload-icon").val('');
                $(".footer-btn__send").prop("disabled", false);
                $('.main-message').animate({ scrollTop: $('.main-message')[0].scrollHeight }, 'fast');
            })

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away