Update attribute with ajax call rails - javascript

I appreciate that there may be many answers out there but if there are i cant quite interpret them to suit my needs..I am looking to update a records attribute in my model using ajax.
In my case the attribute selected: true
In my scenario i am clicking on an element and looking to update that elements record in the model
<ul class="components">
<% #component.each do |c| %>
<li id="<%= c.component_name %>" data-id="<%= c.id %>" data-remote="true"><%= c.component_name %></li>
<% end %>
</ul>
jQuery
$('#Literacy, #Numeracy').on('click', function(){
var component_name = $(this).text();
var component_id = $(this).data('id');
data_send = { id: component_id }
$.ajax({
method: 'put',
url: '/components/selected_component',
data: data_send,
success: function(data) {
console.log(data)
}
});
});
Controller
def selected_component
#component = Component.find(params[:id])
#component.update_attributes(selected: true)
end
Maybe im looking at this incorrectly but how can i get the id via the click event (stored as component_id) into my selected_component method
Im missing a few bits here but struggling with what today
At the moment I am getting an error
Missing template components/selected_component
but i dont want to render that page after successful update, I just want to stay on the same page
EDIT
to solve my issue i just had to add this to my format.js
{ render nothing: true }

A missing template error corresponds to not having a view that knows what to do when it gets a JavaScript request.
In your views/components/, just make an selected_components.js.erb file and that should clear the error you're getting.

Related

Re-render a page using jquery

In react, I could easily re-render a view by passing results from controller. I wish not to use React at this stage and was wondering if it's possible with JQuery?
I have few objects on page, and when clicked, I should see its content. Click the other object, I see its content etc. Sense? I was inspired by this dribbble.
I may not be doing this the right way but this is what I have:
Controller:
def index
selected_contract = params[:selected_contract] || current_user.contracts.last.id
#contracts = current_user.contracts.order(created_at: :desc).all
#selected_contract = current_user.contracts.find_by(id: selected_contract)
end
View:
<% #contracts.each do |contract| %>
<button class="ui button test" id="<%=contract.id%>"><%=contract.name%></button>
<% end %>
......................................
When clicked, show its content
....................................
<%= #selected_contract.name %>
JS:
$( ".ui.button.test" ).click(function(e) {
let { id } = this
console.log(id)
$.ajax({
url: `/url/${id}`,
type: 'POST',
success: function(result) {
//$('#listview').redraw()
console.log('success')
}
});
});
Routes are set properly so I get the params in the controller just fine. Is there a re-render a view, just like rerender a prop in React for jquery? Am I doing this the correct way?
If you are using jquery listview this should work.
$( "#listview" ).listview( "refresh" );
Reference
https://api.jquerymobile.com/listview/#method-refresh
or since its rails you can reload or render the partial view in your server side as well.

calling .val() on date_select element returning undefined?

I'm trying to obtain the selected date from a date_select:
<%= form_for(#newevent) do |f| %>
<%= f.date_select :day, { id: "date-select"} %>
<button id="check-button" type="button">Check</button>
<% end %>
using JQuery/Javascript:
$(document).on('click', "#check-button", function(){
var selectedDate = $("#date-select").val();
alert(selectedDate);
var checkList = []; //creates array to store customer ids
$("#check-list li input").each(function(){ //for each listed colleague...
if( $(this).is(":checked")){ //if check-box is ticked
checkList.push($(this).val()); //add id to list
}
});
$.ajax({
url: '/events/check',
data: {checkList: checkList , selected_date: selectedDate },
method: "POST"
}
);
});
for reference here is where :day is defined in my migration file:
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.timestamps
t.references :calendar, foreign_key: true
...
t.date :day
...
end
However, on alert the returned value is "undefined". Why is this happening? I would like it to return the a value in the form YYYY-MM-DD. Apologies if this is obvious, but I am new to programming and can't seem to fix this one myself
Date_select, according to the rails api "Returns a set of select tags (one for year, month, and day)". Your javascript is going to have to deal with three separate selects and construct a date from them. Look at your generated HTML to get the id's.

Rails: Why can't my object created by ajax be used to trigger javascript?

I'm trying to implement an ajax voting system for a model "Things", where if a user votes on Thing then a new Thing appears in the old one's place, which he can then vote on, and so on. This takes place on the Thing view itself.
I'm pretty sure this exact code was working a week ago, but now it mysteriously broke. Now, the Thing is replaced upon the first vote, but after that, voting no longer brings forth a new Thing:
views/things/show.html.erb
<div id="randajax">
<%= link_to image_tag("UpArrowGray.jpg", class: "rand_up_vote"), upvoterandom_thing_path(#rand.id), remote: true, method: :get %>
<script type="text/javascript">
function reload_script() {
$(".rand_up_vote").click(function () {
$.get( "<%= upvoterandom_thing_path(:id => #rand.id) %>", function( data ) {
$('#randajax').html(data);
reload_script();
});
});
}
reload_script();
</script>
</div>
controllers/things_controller.rb
def upvoterandom
#thing = Thing.find(params[:id])
UpVote.create!
#rand = Thing.all.first
render text: "<a data-method=\'get\' data-remote=\'true\' href=\'" + upvoterandom_thing_path(#rand.id) + "\'><img alt=\'Upvote\' class=\'rand_upp_vote\' src=\'/assets/UpArrowGray.jpg\' /></a>".html_safe
end
Apparently the issue is that an item created with ajax can't execute javascript. The web console shows that the upvoterandom_thing_path is getting executed, but nothing happens to the randajax div. I tried giving the Thing created from the original javascript a differenc class with different javascript and that didn't work either, although a seperate item ("THIS_WORKS") with the same class executed the same javascript normally:
views/things/show.html.erb
<%= link_to "THIS_WORKS", "#", class: "TEST_TEST", remote: true %>
<div id="randajax">
<%= link_to image_tag("UpArrowGray.jpg", class: "rand_up_vote"), upvoterandom_thing_path(#rand.id), remote: true, method: :get %>
<script type="text/javascript">
function reload_script() {
$(".rand_up_vote").click(function () {
$.get( "<%= upvoterandom_thing_path(:id => #rand.id) %>", function( data ) {
$('#randajax').html(data);
reload_script();
});
});
}
reload_script();
</script>
<script type="text/javascript">
$(".TEST_TEST").click(function () {
$('#randajax').html("TEST");
});
</script>
</div>
controllers/things_controller.rb
def upvoterandom
#thing = Thing.find(params[:id])
UpVote.create!
#rand = Thing.all.first
render text: "<a data-method=\'get\' data-remote=\'true\' href=\'" + upvoterandom_thing_path(#rand.id) + "\'><img alt=\'Upvote\' class=\'rand_up_vote\' src=\'/assets/UpArrowGray.jpg\' /></a>".html_safe
end
Can anyone explain why this is happening or how I can fix this?
When you set it up, you do this in your javascript:
$(".rand_up_vote").click(function () {
...
This sets up the click event on the elements. When one of the elements is replaced, or a new one is added, it hasn't had this event added to it, so it won't work like the others.
To fix this, you need to add this same event to the new element, OR remove the event from all elements and then add it to all elements (if you don't remove it first you risk firing the same event twice on a click or whatever).
EDIT with a proposed solution.
The simplest way is to add an onclick attribute to your elements, to run the reload_script() function. Change this so that it doesn't add an onclick to the events. I was about to start editing your code and i noticed that the reload_script function calls itself at the end of the anonymous function you're adding as the onclick event: this means that when you click on a .rand_up_vote element, it will do the AJAX get, replace the html, and then add another onclick to all the elements. This is definitely not right - was this an earlier attempt to fix this problem?
You probably just need something like this:
<div id="randajax">
<%= link_to image_tag("UpArrowGray.jpg", class: "rand_up_vote"), upvoterandom_thing_path(#rand.id), remote: true, method: :get %>
<script type="text/javascript">
function reload_script() {
$.get( "<%= upvoterandom_thing_path(:id => #rand.id) %>", function( data ) {
$('#randajax').html(data);
});
}
</script>
</div>
now edit the html so that each .rand_up_vote element has an onclick="reload_script()" attribute.

Rails 4 / Ruby 2: Local variable (FormBuilder) for partial is lost through dynamic update

I have this form that renders a partial for selecting a person's task.
new.html.slim:
= form_for(#person) do |f|
= f.text_field :name
= f.fields_for :assignment do |a|
= a.collection_select :project_id, Project.order(:name), :id, :name
div id="task_list"
= render 'shared/_task_select', a: a
= f.submit 'Save'
shared/_task_select.html.slim:
= a.collection_select :task_id, #tasks, :id, :name
Changing the project triggers a javascript that runs a "create_tasklist"-method in the PersonsController.
new.js:
$(document).ready(function() {
$('#person_assignment_attributes_project_id').change(function() {
var selection = $('#person_assignment_attributes_project_id').val();
$.ajax({
url: "/create_tasklist",
data: {
project_id : selection
},
dataType: "script"
});
});
});
The "create_tasklist"-method triggers a javascript that updates the partial:
create_tasklist.js.erb:
$("#task_list").html("<%= escape_javascript(render 'shared/task_list', a: a) %>");
Now this raises the error:
undefined local variable or method `a' for #<#<Class:0x42cd770>:0x4213ef0>
The same form works well when editing existing persons - until changing the project. Thus, FormBuilder "a" loses its definition through the javascript actions. I have to use a partial here because I want to do more stuff with it in a later stage. Any ideas how to get that variable to keep its defintion?
Edit 1:
I already tried adding this below the third line of new.html.slim:
javascript:
var a = "#{a}";
and then adding: a: a in the "data" declaration of new.js.
Edit 2:
With this the FormBuilder seems to pass through until the "create_tasklist"-method, but I do not know how to access it properly there. If I declare ´#a = params[:a]´ in the "create_tasklist"-method and then use (in create_tasklist.js.erb):
$("#task_list").html("<%= escape_javascript(render 'shared/task_list', a: #a) %>");
I recieve the error:
undefined method `collection_select' for "#<ActionView::Helpers::FormBuilder:0x4760400>":String
So the FormBuilder has become a string but a least it "got through" somehow. How can I leave it intact and is a more efficent way to achieve this?

Using jQuery to update multiple objects

I have a profile page where I render all of the user's lists using a partial:
users/show.html.erb
<%= render #lists %>
For each list I show how many wishes are associated:
lists/_list.html.erb
<p class="muted" id="wishes_count"><%= pluralize(list.wishes.count, "wish") %></p>
I'm using drag and drop to allow the user to move wishes from one list to another using jQuery sortable.
Right now, I'm using the following code:
wishes.js.erb
$(document).ready(function(){
$('.user_list_wishes').sortable({
connectWith: ".user_list_wishes",
items: ".user_list_wish",
placeholder: "sortable_placeholder",
update: function(e, ui)
{
if (this === ui.item.parent()[0])
{
item_id = ui.item.data('item-id');
list_id = $(this).data('list-id');
position = ui.item.index();
$.ajax({
type: 'POST',
url: $(this).data('update-url'),
dataType: 'json',
data: { id: item_id, wish: { row_order_position: position, list_id: list_id } }
}),
$("#wishes_count").html('<%= pluralize(list.wishes.count, "wish") %>')
}
}
})
})
This line of code:
$("#wishes_count").html('<%= pluralize(list.wishes.count, "wish") %>')
makes my application throw a NoMethodError undefined method 'wishes' for nil:NilClass
I believe it has something to do with how I render lists and reference them individually in my javascript?
Any suggestions on how to solve this problem is much appreciated!
You must handle the scenario where list is null using the following condition:
$("#wishes_count").html('<%= pluralize(list ? list.wishes.count : 0, "wish") %>')
I think the problem could be in your render call - according to the documentation:
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
<%= render #customer %>
Assuming that the #customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it and will pass the local variable customer into the partial which will refer to the #customer instance variable in the parent view.
So check that this is the case - do you have a partial called _lists.html.erb and a parent variable called list?

Categories

Resources