Asynchronous communication introduces conversation functionality, but data cannot be displayed without reloading the page.

Asked 2 years ago, Updated 2 years ago, 47 views

I am thinking of introducing a conversation function through asynchronous communication.Data can be displayed without page movement, but it cannot be displayed without page movement or reloading.If anyone knows, please let me know how to do it.

if Entry.where(:user_id=>current_user.id,:room_id=>params[:message][:room_id]).present?
    @message=Message.new(params.require(:message).permit(:user_id,:content,:room_id).merge(:user_id=>current_user.id))
    [email protected]
        response_to do | format |
            format.html {redirect_to:action=>"show",:controller=>"rooms",:id=>@message.room_id}
            format.json 
        end
    end
else
    redirect_back(fallback_location:root_path)
end
<%[email protected] event?%>
    <%@messages.each do | m | %>
    <strong><%=m.content%></strong>
    <small>by<strong><a href="/users/<%=m.user_id%>">%=m.user.email%>%>san</a>/strong>></small>
    <hr>
<%end%>
<%else%>
    <h3class="text-center"> No message yet</h3>
<%end%>

<%=form_for@message, id:"new_message" do | f | %>
    <%=f.text_field:content, class: "form__message", :placeholder=> "Please enter a message", :size=>70%>
    <%=f.hidden_field:room_id, class:"form_message",:value=>@r oom.id%>
    <br>
    <%=f.submit "Post", class: "form__message"%>
<%end%>
<script type="text/javascript">
    $(document).ready(function(){

        $('#new_message').on('submit', function(e){
            e.preventDefault();
            var formData = new FormData(this);
            var url = $(this).attr('action');
        })
    }

    $("#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
        })
    }

    $(document).ready(function(){
        function buildHTML (message) {
        var html=`<div class="message">
                        <div class="upper-message">
                            <div class="upper-message__user-name">
                                ${ content}
                            </div>
                        </div>
                    </div>`;
        }
        return false;

        function scroll() {
            $('.messages') .animate({scrollTop:$('.message')[0].scrollHeight});
        }

        $("#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
            });

            .done(function(data){
                var html = buildHTML(data);
                $('.messages').append(html);
                $('.form__message').val(');
                $('.form__submit').prop('disabled', false);
            });
            scroll()
        });
    };
</script>

·jbuilder

javascript ruby-on-rails ruby jquery

2022-09-30 20:10

2 Answers

Simple grammar error? Is it because $.ajax() followed by .done() before connecting ?


2022-09-30 20:10

Let's isolate the problem.

[1. Are there any basic mistakes made by js or jQuery?]]

·$(...).on binding outside ready is not common.
 If you don't understand the processing order clearly, you should avoid it.
 Also, $(handler) is recommended for jQuery 3.0 and later.

·There seems to be a mistake in javascript
 As for buildHTML(), does it look like you don't use the message argument...?Also, let's arrange the indentation.

[2. Separation around Ajax treatment]

Rails View (that is, generated html itself) may be incorrect
  → Press F12 on chrome to see if the actual generated html DOM is as you expected

The server side may not be doing well for the URL called by Ajax.
 → It should be possible to text out the log with the appropriate function.
   Verify that the expected server-side controller is called.

Ajax communication may have failed
 → As a prerequisite, Ajax should always write done, fail, always as a set.
   See the ajax reference for more information.
   Also, check which of these was done with alert() or console.log()
  Ajax communication has several restrictions
  ·If the page itself and Ajax request destination are not the same source (cross-domain),
   Server side fails if CORS is not addressed
  ·If it is a GET request, it is possible to avoid it with jsonp, but if it is a jsonp,
   Cannot read cause of error when error occurs


2022-09-30 20:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.