Updating Elements in Rails with Ajax

Rails update element based on AJAX request?

Your description is quite correct!
Opposed to the other answer, you don't even need a event listener but as you said you want to have a respond_to in the controller.
So starting from the html:

# post/index.html.erb
<div id="like-button">
<%= button_to "Like this post", post_path(@post), remote: true %>
</div>

Note, that when you use a button_to helper it'll be a POST request by default.

If you click it, it'll go to the controller#update, which you want to change to this:

#posts_controller.rb
...
def update
@post.save
respond_to do |format|
format.html { redirect_to post_path(@post) }
format.js # <-- will render `app/views/posts/update.js.erb`
end
end

Note: the format.html is rendered when JS is disabled.
Now in the scenario that JS is enabled, it executes the app/views/posts/update.js.erb file. It can look like this:

const likeButton = document.getElementById('like-button');
likeButton.innerHTML = '<%= j render "posts/liked-link", post: @post %>';

What is the last line doing? Of course, you can change the style directly with the JavaScript, but you can also render a new partial - and this you will create in a new html file:

# app/views/posts/liked_link.html.erb
<div id="like-button ">
<p>"You liked this post!" </p>
</div>

I just changed the link/button to ap now, but of course you can do whatever you want.

Hope that makes sense :)

In rails, updating a div with Jquery/Ajax

You almost done everything.

The only remaining part is to put team information into a partial, named e.g. _team.html.erb:

<div class ="team-list" id="team_<%=team.id%>">
<div class= "boxin1"><%= team.name %></div>
<div class= "boxin2"><%= team.win %></div>
<div class= "boxin2"><%= team.loss %></div>
<div class= "boxin2"><%= team.tie %></div>
<span class= "boxin3 btn btn-primary"><%= link_to "Edit", edit_scoreboard_team_path(@scoreboard, team), remote: true %> </span>
<span class= "boxin3 btn btn-primary"><%= link_to "Del", [@scoreboard, team], remote: true, method: :delete, data: { confirm: "Are you sure you want to delete the team?" } %>
</div>

and then update.js.erb:

$("#edit_team_<%=@team.id%>").hide();
$("#team_<%=@team.id%>").load("<%= j render partial: 'team', locals: {team: @team} %>");
$("#team_<%=@team.id%>").show();

Update DB with ajax request in rails

Don't use $.get() to make calls that update data. Send the request via PUT instead. Since you're updating all of the user's activity, you don't need to do an Activity.find lookup. I'm assuming your User model has a 'has_many :activities' association defined. Your JS would look like this (I'm using coffeescript):

$('#bell-notices').click ->
$bell = $(this)
$bell.find('.notifications-count').hide '0'
$bell.parent().find('.dropdown-toggle').dropdown()
$.ajax
url: '/activities/mark_activity_viewed'
type: 'put'

(as JS):

$('#bell-notices').click(function() {
var $bell;
$bell = $(this);
$bell.find('.notifications-count').hide('0');
$bell.parent().find('.dropdown-toggle').dropdown();
$.ajax({
url: '/activities/mark_activity_viewed',
type: 'put'
});
});

In your activities_controller, you would have:

def mark_activity_viewed    
current_user.activities.update_all(viewed: true)
[any respond_to stuff you care to do...]
end

You need to have a route in routes.rb that matches the 'put'

put 'activities/mark_activity_viewed' => 'activities#mark_activity_viewed'

Note that the 'update_all' above will skip validations on Activity, but since all you're doing here is changing a boolean value, this shouldn't be an issue. If you want validations on each Activity to be performed, loop through them and do the typical update and save!

Which controller you put this in is really up to you. I would put it in the users_controller, since it is a more user-centric action, but there's nothing wrong with leaving it in the activities controller.

Rails AJAX Update on Select

Here's how I got this to work correctly:

pf_orders_controller.rb

def update_receiver_status
@pf_order = PfOrder.find(params[:id])
if @pf_order.update_attributes(pf_order_params)
render json: @pf_order.as_json, status: :ok
else
render json: {pf_order: @pf_order.errors, status: :unprocessable_entity}
end
end

def pf_order_params
params.fetch(:pf_order, {}).permit(:sequence_number, :message_guid, :hl7_document, :download, :post_status_code, :patient_id, :receiver_status)
end

_pf_order.html.erb

Got rid of the form_for

<%= label :receiver_status, 'Status:' %>
<%= select_tag :receiver_status,
options_for_select(receiver_statuses, pf_order[:receiver_status]),
onchange: "$.post('#{update_receiver_status_pf_order_path(pf_order)}',
{'_method':'patch', 'pf_order[receiver_status]':this.value} );",
class: 'form-control' %>

I removed the jQuery from pf_orders.coffee

routes.rb

resources :pf_orders do
patch :update_receiver_status, on: :member
end

Thanks to Alexandre Angelim for the correct route and pointing me in the right direction.

Rails how to update the page with the help of Ajax

Controller:

def done
@task = Task.find(params[:id]) # make sure you have this
@task.update_attributes(:done => params["done"])

render :json => { data: "Success", is_done: params[:done] }
end

View:

 ....
<td><%= task.done %></td>
<td><%= check_box_tag 'done', task.id , task.done, :class => "task-check" %></td>
....

<script>
$(".task-check").on('change', function(e){
// removed remote-true. you can preventDefault if you need to but doubt page tries to refresh from a checkbox getting checked. e.preventDefault() if you need it
$.ajax({
type: "POST",
url: '/tasks/done',
type: 'POST',
data: {done: $('.task-check').val()},
}).done(function(ajax_response){
// update whatever you want after it completes
});
});

</script>

Didn't test this but I write these all the time. Let me know if it doesn't work post the payload and I'll figure out what's missing.

If you just want to update the value from 'incomplete' to 'complete', you can simply target the element that's called incomplete. if it has a class of, say, 'task-status' you can target that element and update in the .done part of the function. For instance:

$('.task-status').text('Complete')

should replace what previously said incomplete. If it's a text input you might use .val() instead. If it's just text on the page .text() should work.



Related Topics



Leave a reply



Submit