Ajax on rails 4

I have an application that allows users to like a message. When someone likes a message, the mail request works, but the view does not refresh unless I refresh the page. I am stuck on this. This is what I have so far:

Javascript

$('.favorite').on('click', function() {
  var $heart = $(this).find('.fa');
  $heart.removeClass('fa-heart-o').addClass('fa-heart');
  // POST request to server to create favorite in db
  $.post('/favorites', {
    favorite: { post_id: $(this).attr('data-id') }
  },
  function(data) {
    console.log(data);
  });
});

Controller

def create
  post = Post.find_by_id(favorite_params[:post_id])
  if current_user.favorite_posts.include? post
    render json: {}, status: :bad_request
  else
    @favorite = current_user.favorites.new(favorite_params)
    if @favorite.save
      render json: @favorite
    else
      render json: { errors: @favorite.errors.full_messages }, status: :unprocessable_entity
  end
end

end

This view

<% if current_user.favorite_posts.include? post %>
  <span class="fa fa-heart"> <%= post.favorites.count %></span>
<% else %>
  <span class="fa fa-heart-o"> <%= post.favorites.count %></span>
<% end %>

Any help is appreciated. Thanks.

+4
source share
3 answers

There are two solutions:

  • Invoke a view change with the built-in ajax browser
  • Use the Rails UJS function to trigger a view change on the server.

, , - . - , , , :


Ajax

Ajax ; :

$.post('/favorites', { favorite: { post_id: $(this).attr('data-id') }},
.done( function(data) {
  /* Manipulate your view here */
  $("span.fa").text(data);
  console.log("Success");
});

, Ajax - . Javascript -, .

( )... , .


JS

, , Rails UJS. javascript ERB .

, javascript:

$.post('/favorites', { favorite: { post_id: $(this).attr('data-id') }}
  .done( function(data) { console.log(data); });


#app/controllers/favourites_controller.rb
class FavouritesController < ApplicationController
   def create
     ...
     respond_to do |format|
        if @favorite.save
          format.js #-> invokes /views/favourites/create.js.erb
          format.json { render json: @favorite }
        else
          format.js
          format.json { render json: { errors: @favorite.errors.full_messages }, status: :unprocessable_entity }
  end
end

app/views/favourites/create.js.erb :

#app/views/favourites/create.js.erb
$("span.fa").hide();
+2

: -

var new_count;
new_count = function() {
  # your script
};



$(document).ready(new_count);
$(document).on('page:load', new_count);

- turbolink checkthis

+6

function(data) {
  console.log(data);
  });

. , , , , jQuery $( "... span.fa" ).text(new_count).

new_count (previous_count_in_the_span + 1), , .

+2

Source: https://habr.com/ru/post/1608952/


All Articles