Ruby on rails - PUT method on update ajax
Rails determines the put request via the parameter _method with the value 'put'.
As not all the browsers support the put method, rails cheats in the form_tag. its putting this output in a PUT form:
<input type='hidden' name='_method' value='put'>
So what you have to do is this:
$.ajax({
type: "POST",
dataType: "script",
url: '/resources/35',
contentType: 'application/json',
data: JSON.stringify({ resource:{pos_y:45,pos_x:50}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
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 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 :)
Related Topics
How to Add "Href" Attribute to a Link Dynamically Using JavaScript
What Is a Text Node, Its Uses? //Document.Createtextnode()
How to Save Canvas Animation as Gif or Webm
HTML Mobile -Forcing the Soft Keyboard to Hide
When Loading an HTML Page via Ajax, Will Script Tags Be Loaded
How to Resize HTML Canvas Element
How to Retain the Scroll Position of a Scrollable Area When Pressing Back Button
Making Sure at Least One Checkbox Is Checked
How to Append Timestamp to the JavaScript File in <Script> Tag Url to Avoid Caching
Detect Programmatic Changes on Input Type Text
Position Fixed Not Working in Mobile Browser
How to Select All Text in Contenteditable Div
Get the Dom Path of the Clicked <A>
Target='_Blank' to Show in New Window, Not New Tab, Possible
Open a New JavaScript Window(.Open) Along with Its CSS Styling
Es6 Module Import Giving "Uncaught Syntaxerror: Unexpected Identifier"