render records in databales - javascript

I am rendering the data created and edited in a js.erb to a datatable, the problem is that when making use of pagination, such data disappears. this my index:
<table id="superior" class="display"><!--el id activos es de datatables referenciado en activos.coffe y display class es una clase de datatables-->
<thead>
<tr><!--active es para sombrear la fila-->
<th>Id</th>
<th>DescripciĆ³n</th>
<th>Modelo</th>
<th>FechaAlta</th>
<th>Serie</th>
<th>CB</th>
<th>Imagen</th>
<th>Status</th>
<th>Acciones</th>
<th></th>
</tr>
</thead>
<tbody id="container_activos">
<%= render #activos %><!--carga todos los activos-->
</tbody>
</table>
my partial _activo.html.erb
<tr id="activo_<%= activo.id %>">
<td><%= activo.IdActivos %>
</td>
<td><%= activo.Descripcion %></td>
<td><%= activo.Modelo%> </td>
<td><%= activo.Fecha%>></td>
<td><%= activo.Serie %></td>
<td><%= activo.CB %></td>
<td id="producto-imagen" >
<%= image_tag activo.cover.url(:minithumb) %>
</td>
<td><%= activo.Status %>
</td>
<td>
<button type="button" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#myupdateactivo_<%= activo.id %>">
Editar
</button>
</td>
<td>
</td>
</tr>
my create.js.erb:
$("#mynewactivo").modal('hide');
$("#container_activos").prepend('<%= j render #activo %>'); //Prepend before append
$("#activo_<%= #activo.id %>").hide().fadeIn(1000);
$("#notice").html("<%= escape_javascript(render :partial => 'partials/flash' , :locals => { :flash => flash }).html_safe %>");
setTimeout(function(){
$('#notice').fadeIn("slow", function() {
$(this).create();
})
}, 1500);
my update.js.erb:
$("#myupdateactivo_<%= #activo.id %>").modal('hide');
$("#mynewactivoenvase").modal('show');
$("#activo_<%= #activo.id %>").fadeOut(500, function(){
$(this).remove();
$(".child").remove();
$("#container_activos").prepend('<%= j render #activo %>');
});
$("#notice").html("<%= escape_javascript(render :partial => 'partials/flash' , :locals => { :flash => flash }).html_safe %>");
setTimeout(function(){
$('#notice').fadeIn("slow", function() {
$(this).create();
})
}, 1500);

Related

How would I getElementById from a Rails View

I have a Rails view with the following HTML:
<tbody>
<% #requests.each do |request| %>
<tr data-request-id="<%= request.id %>">
<td id="artist" style="text-align: center"><%= request.artist %></td>
<td style="text-align: center"><%= request.title %></td>
<td style="text-align: center" class="voteCount"><%= request.voteCount %></td>
<td style="text-align: center"><%= button_to 'Vote', request_upvote_path(request.id), remote: true, method: :post, onclick: 'upVote()', class: 'upVote' %></td>
</tr>
<% end %>
</tbody>
I'm trying to access the voteCount cell in the table, but I'm not sure how to do it. Normally in JS I would use document.GetElementById or GetElementBysClassName
I have a method that increments the voteCount number by 1 when the button is clicked, which works fine, but this JS function needs to increment the correct request.
Here's the current JS:
function upVote() {
var count = document.getElementsByClassName("voteCount")[0].innerHTML;
count = parseInt(count);
count = count + 1;
count = count.toString();
document.getElementsByClassName("voteCount")[0].innerHTML = count;
document.getElementsByClassName("upVote")[0].disabled = "true";
}
Try something like this. You can pass the id onclick with rails and the just use the regular getElementById in JavaScript:
<tbody>
<% #requests.each do |request| %>
<tr data-request-id="<%= request.id %>">
<td id="artist" style="text-align: center"><%= request.artist %></td>
<td style="text-align: center"><%= request.title %></td>
<td style="text-align: center" id="voteCount<%= request.id %>"><%= request.voteCount %></td>
<td style="text-align: center"><%= button_to 'Vote', request_upvote_path(request.id), remote: true, method: :post, onclick: "upVote(#{request.id})", class: 'upVote', id:"voteButton#{request.id}" %></td>
</tr>
<% end %>
function upVote(id) {
var count = document.getElementById("voteCount" + id).innerHTML;
count = parseInt(count);
count = count + 1;
count = count.toString();
document.getElementById("voteCount" + id).innerHTML = count;
document.getElementById("voteButton" + id).disabled = true;
}

Displaying MySQL query results as HTML with EJS

I am building an app (using EJS view engine and Node.js) which interacts with an MySQL database I have built locally. I can receive results from my queries successfully as a JSON string, but I cannot send the information to a view (to be displayed as HTML) as I am getting the error: unsafefoods is not defined.
My 'app.js' file declares:
var unsafefoods = require('./routes/unsafefoods');
app.use('/unsafefoods', unsafefoods);
My route 'unsafefoods.js' declares:
var express = require('express');
var router = express.Router();
/* GET all safe foods */
router.get('/', function (req, res, next) {
connection.query('SELECT * from appycavy.foods WHERE safe = 0', function (error, rows, fields) {
if (error) {
res.send(JSON.stringify({
"status": 500,
"error": error,
"response": null
}));
//If there is error, we send the error in the error section with 500 status
} else {
res.render(unsafefoods, {
title: 'Unsafe foods list',
data: rows
})
}
});
});
module.exports = router;
And my view 'unsafefoods.ejs' declares:
<!DOCTYPE html>
<html lang="en">
<head>
<% include ./partials/head %>
</head>
<body class="container">
<header>
<% include ./partials/header %>
</header>
<main>
<div class="jumbotron">
<h2>Safe foods</h2>
<p>The following is a list of all
<b>unsafe</b> foods
</p>
<!-- table to display unsafe foods -->
<table width='80%' border=0>
<tr style='text-align:left; background-color:#CCC'>
<th>ID</th>
<th>Name</th>
<th>Safe</th>
<th>Type</th>
<th>Favourite</th>
<th>Water</th>
<th>Energy</th>
<th>Vitamin C</th>
<th>Sugar</th>
<th>Lipid fat</th>
<th>Calcium</th>
<th>Phosphorus</th>
<th>CaP ratio</th>
</tr>
<!--
Using FOREACH LOOP for the users array
myArray.forEach(function(el, index) {
// el - current element, i - index
});
-->
<% if (data) { %>
<% data.forEach(function(unsafefoods){ %>
<tr>
<td><%= unsafefoods.id %></td>
<td><%= unsafefoods.name %></td>
<td><%= unsafefoods.safe %></td>
<td><%= unsafefoods.type %></td>
<td><%= unsafefoods.favourite %></td>
<td><%= unsafefoods.water %></td>
<td><%= unsafefoods.energy %></td>
<td><%= unsafefoods.vitaminC %></td>
<td><%= unsafefoods.sugars %></td>
<td><%= unsafefoods.lipidFat %></td>
<td><%= unsafefoods.calcium %></td>
<td><%= unsafefoods.phosphorus %></td>
<td><%= unsafefoods.capRatio %></td>
<td>
<div style="float:left">
<a href='/unsafefoods/edit/<%= unsafefoods.id %>'>Edit</a>
<form method="post" action="/unsafefoods/delete/<%= unsafefoods.id %>" style="float:right">
<input type="submit" name="delete" value='Delete' onClick="return confirm('Are you sure you want to delete?')" />
<input type="hidden" name="_method" value="DELETE" />
</form>
</div>
</td>
</tr>
<% }) %>
<% } %>
</table>
</div>
</main>
<footer>
<% include ./partials/footer %>
</footer>
</body>
</html>
Any pointers would be appreciated,
Thanks,
unsafefoods variable is undefined in your unsafefoods.js file.
Your code should be
res.render('unsafefoods', {
title: 'Unsafe foods list',
data: rows
})
you are missing '' around unsafefoods.

select2 breaks with ajax/jquery on pagination

I have a Rails 3.2.21 app which I use select2 for my dropdown menus and UI. In this view I'm doing a multi-select to pick different elements/objects in my view/form. When the initial controller view loads it's fine as you can see by the first picture. But when I click to a second page to paginate, the select2 is broken by the Ajax as you can see in the last picture.
Here is what my view looks like:
index.html.erb
<h3 class="offset3">5 most recent pages</h3>
<div class="row">
<div class="span3"><div class="well" id="form"><%= render 'form' %></div></div>
<div class="span9"><div id="pages"><%= render 'pages' %></div></div>
</div>
index.js.erb
$("#form").html("<%= escape_javascript render("form") %>");
$("#pages").html("<%= escape_javascript render("pages") %>");
_form.html.erb
<%= form_for(#page) do |f| %>
<div class="control-group">
<div class="controls">
<%= f.label :message %>
<%= f.text_area(:message, size: "40x2", :maxlength => 254, placeholder: "Enter your message here", required: true) %>
<%= f.label 'Unit'%>
<%= f.select :unit_id, options_for_select(Unit.active.order(:unit_name).map{ |unit| [unit.unit_name, unit.id] } + [["All Units", "all"]]), {:include_blank => true}, {:multiple => 'true', class: 'select'} %>
<%= f.label 'Region' %>
<%= f.collection_select(:region_id, Region.order("area ASC"), :id, :area, {:include_blank => true}, {:multiple => 'true', :class => 'select' } )%>
</div>
</br>
<%= f.button 'Send Page', class: 'btn btn-info', data: {disable_with: "<i class='icon-spinner'></i>Sending..."} %>
</div>
<% end %>
_results.html.erb
<table class="table table-striped">
<thead>
<tr>
<th>Incident Number</th>
<th>Patient Name</th>
<th>Transfer Date</th>
<th>Transferred From</th>
<th>Transferred To</th>
<th>Determinant</th>
<th>Unit</th>
<th>Insurance</th>
<th>Cancelation Reason</th>
<th>Billing Reference</th>
<th>Run Time</th>
<th></th>
</tr>
</thead>
<tbody>
<% #calls.each do |c| %>
<tr>
<td><%= c.incident_number %></td>
<td><%= c.patient_name %></td>
<td><%= c.transfer_date.strftime("%m/%d/%y") %></td>
<td><%= transferred_from(c) %><br/><%= transferred_from_address(c) %></td>
<td><%= transferred_to(c) %><br/><%= transferred_to_address(c) %></td>
<td><%= c.nature.try(:determinant)%></td>
<td><%= c.units.map(&:unit_name).join(", ") %></td>
<td><%= c.insurance.try(:insurance_type)%></td>
<td><%= c.cancel_reason.try(:reason) %></td>
<td><%= c.imx_num %></td>
<td><%= TimeFormatter.format_time(c.run_time) if c.in_service_time? %></td>
<td><%= link_to 'View', c, :class => 'btn btn-info btn-mini'%></td>
</tr>
<% end %>
</tbody>
</table>
<%= will_paginate #calls, :renderer => BootstrapPagination::Rails %>
Here is the jQuery from my application.js file:
$(function (){
$(".select").select2({
placeholder: "Select One",
allowClear: true
});
$(function() {
$("#pages th a, #pages .pagination a").live("click", function() {
$.getScript(this.href);
return false;
});
});
It looks like when I click a pagination link the dom is not getting reloaded and thus breaking the UI with select2. I can still pick objects in the form but UI-wise it's broken.
I was wondering if anyone could help point me in the right direction with this as I'm not very savvy with jQuery or javascript/ajax.
If my question is not clear or you need further examples, please let me know.
working
breaks on ajax pagination
So far this is the only useful answer I've come up with.
In my index.js.erb file I put the following:
$("select").select2({
placeholder: "Select One",
allowClear: true
}); init();
This will reinitialize select2 by destroying the call on an Ajax request then calling select2 again. It behaves as expected and keeps the UI properties while overriding the "turbolinks-like" Ajax behavior.
This is working 100% for me, although it feels a bit hackish that I have to do this in UJS, but hey whatever works right?

Iterate over an array by index when click on submit button Ruby on Rails

I have an array of Pet instances and each of them have a name, type, sex and size, etc... I'd like to iterate through this collection of Pet instances and display the each one by one.
This is what I have so far:
<% #pets.each do |pet| %>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Sex</th>
<th>Age</th>
<th>breed</th>
<th>Size</th>
<th>Picture</th>
<th>Description</th>
<th>Shelter_id</th>
<th>Shelter</th>
<th>Phone</th>
<th>Email</th>
<th>City</th>
<th>Zip</th>
<th>Like</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= pet.name %></td>
<td><%= pet.species %></td>
<td><%= pet.sex %></td>
<td><%= pet.age %></td>
<td><% pet.breeds.each do |breed| %>
<li><%= breed.name %></li>
<%end%>
</td>
<td><%= pet.size %></td>
<td><%= image_tag pet.picture %></td>
<td><%= pet.description %></td>
<td><%= pet.shelter_id %></td>
<% shelter = Shelter.find(pet.shelter_id)%>
<td><%= shelter.name %></td>
<td><%= shelter.phone %></td>
<td><%= shelter.email %></td>
<td><%= shelter.city %></td>
<td><%= shelter.zip %></td>
<td><%= form_for pet, :url => { :controller => "favorite_pets", :action => "create" }, :html => {:method => :post} do |f| %>
<%= f.text_field :id %>
<%= f.submit %>
<% end %>
</td>
</tr>
</tbody>
</table>
<%end%>
So now, I need two thinks.
1st
When a user clicks the submit button (<%= f.submit %>) to send a POST request i do not want the page to reload nor to redirected me to another page. I looked around and it seems like :remote => true included in the form_for would do the trick but i'd need more help with that.
2nd
I'd like to control the iterating through #pets so that only the first one is displayed pet[0] and every time I click on the <%= f.submit %> button not only does it not reload the page but it displays the next index in the array pet[1]
I think I need to set up a sort of counter which would increment the index of the pet array every time a user click on the <%= f.submit %> button.
Any guiding thoughts?
If I were to do this I would use some javascript. So your submit button turns into more of an "Add Button" it doesn't actually submit anything. It would just add that object (in your case the pet, along with its info) to a javascript array as well as display the new object (again the pet along with the info) on the window. Then create another button to actually submit all the pets. (The javascript array)

Rails jQuery sortable unable to save

I'm trying to make my table sortable (drag and drop) using jQuery, the problem I'm having is saving the new sorted table and then publishing it to other users or when the browser is refreshed.
I'm using:
gem 'acts_as_list'
Rails 3.2.17
ruby 1.9.3p484
Is there a better way of doing this?
my sort and show method on my controller
def sort
#episodes = current_user.episodes_for(#show).each do |episode|
episode.position = params['episode'].index(episode.id.to_s) + 1
episode.save
end
render :nothing =>true
end
def show
#episodes = current_user.episodes_for(#show)
#episodes.order('episode.position ASC')
#episode = #episodes.where(id: params[:id]).first
end
My Javascript
<script>
$(window).load(function() {
$("#sortthis").sortable({
axis: 'y',
placeholder: 'ui-state-highlight',
cursor: 'move',
dropOnempty: false,
scroll: true,
opacity: 0.4,
update: function(event, ui){
var itm_arr = $("#sortthis").sortable('toArray');
var pobj = {episodes: itm_arr};
$.post("/episodes/sort", pobj);
}
});
});
</script>
The table I wanna sort in views:
<tbody id='eps'>
<tr>
<th>Title</th>
<th>#</th>
<th>Season</th>
<th>Download?</th>
<th>Shared?</th>
<th>Length</th>
<th>Status</th>
<th></th>
</tr>
<% for episode in #episodes %>
<tr>
<td id="eps_<%= episode.id %>", width="20%"><%=h episode.title %></td>
<td id="eps_<%= episode.id %>"><%=h episode.number %></td>
<td id="eps_<%= episode.id %>"><%=h episode.season %></td>
<td id="eps_<%= episode.id %>"><%=h episode.is_downloadable %></td>
<td id="eps_<%= episode.id %>"><%=h episode.shared_with_dev %></td>
<td id="eps_<%= episode.id %>"><%=h episode.length %></td>
<td>
<% if episode.video %>
<%= link_to 'Replace Video', new_show_episode_video_path(episode.show, episode) %>
<% else %>
<%= link_to 'Upload Video', new_show_episode_video_path(episode.show, episode) %>
<% end %>
</td>
<td>
<%= link_to "View", [episode.show, episode] %>
<%= link_to "Edit", edit_show_episode_path(episode.show, episode) if permitted_to? :update, episode %>
<%= link_to "Delete", show_episode_path(episode.show, episode), :confirm => 'Are you sure?', :method => :delete if permitted_to? :delete, episode %>
</td>
</tr>
<% end %>
any help will be greatly appreciated!
I figured it out, made the following changes:
Views:
<tr id="<%= episode.id %>">
and new controller
def sort
Episode.all.each do |e|
if position = params[:episodes].index(e.id.to_s)
e.update_attribute(:position, position + 1) unless e.position == position + 1
end
end
render :nothing => true, :status => 200
end
finally added this to my model:
acts_as_list
default_scope order('position')
let me know if anyone's having similar issues.

Categories

Resources