I have this page made using node.js + express where I am displaying the following table :
I wish to reload only the table with new data using ajax when limit is changed using the dropdown (one with the label show result), but am having trouble doing so.
Here's the ejs code that displays my table :
<table class="assignment-table table table-striped table-bordered table-hover table-condensed table-responsive">
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>Subject</th>
<th>Topic</th>
<th>Faculty</th>
<th>Posted</th>
<th>Last Date</th>
<th>Mode of Submission</th>
</tr>
</thead>
<tbody class="table_body">
<% for(var i =0;i< result.length;i++) { %>
<tr>
<td class="result_id">
<a target="_blank" href="/assignment/abc.pdf" class="download-link" id="">
<%= result[i]._id %>
</a>
</td>
<td class="result_name">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].nameAssignment %>
</a>
</td>
<td class="result_subject">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Subject %>
</a>
</td>
<td class="result_topic">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Topic %>
</a>
</td>
<td class="result_faculty">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Faculty %></a>
</td>
<td class="result_posted">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Posted %></a>
</td>
<td class="result_lastdate">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].LastDate %></a>
</td>
<td class="result_submission">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Submission %></a>
</td>
</tr>
<% } %>
</tbody>
</table>
In the filter_result() route mentioned above, I am fetching limit from the url and querying the database with new limits and rendering the page again.
Router.get('/filter_result',(req,res) => {
limit = parseInt( decodeURIComponent(req.query.limit) );
models.filterResults(limit, (count,result) => {
//if (err) throw err;
console.log(limit);
//res.send(result);
res.render('assignment-list',{limit:limit,result:result,count : count});
});
});
How can I redisplay the table in the ejs page?
Basically your .ejs format is rendered only once when you load or reload the page. So what you do is re-render (or, replace) the HTML from your AJAX call on top of already-rendered HTML.
It seems that you're using jQuery already so my example code uses jQuery too.
Re-rendering (or, again, replacing) HTML depends on what your /filter_result responds. If it's just bunch of <tr>s then it might be
JS
$('table.assignment-table').find('tbody').html(result);
If it's the entire <table> then you'd better wrap <table> with some wrapper like <div> and do the following.
HTML
<div id="table-wrapper">
<table>
...
</table>
</div>
JS
$('div#table-wrapper').html(result);
How you refer your wrapper and replace the content can vary.
Update 1
Assuming your API (/filter_result) returns an array of assignment objects like
{
"status": "success",
"data": [
{
"Subject": "Your subject",
"Topic": "Your topic",
...
},
...
]
}
you can create bunch of <tr/>s from data and replace the existing <tr/>s with them like (with jQuery of course. About creating DOM with jQuery, you can refer the docs.)
$.ajax({
method: 'GET',
url: 'URL_TO_FILTER_RESULT',
data: SOME_DATA,
success: function(res) {
var assignments = res.data;
var body = [];
assignments.forEach(function(assignment) {
var tr = $('<tr/>');
tr.append($('<td/>').html('' + assignment.Subject + '');
tr.append($('<td/>').html('' + assignment.Topic + '');
...
body.push(tr);
});
$('table.assignment-table').find('tbody').html(body);
}
})
Related
$(".collapse.summary_row_<%= pin %>").each(function() {
var thisId = $(this).find('#pin').text();
var sumVal = parseFloat($(this).find('#price').text());
var $rowsToGroup = $(this).nextAll('tr').filter(function() {
return $(this).find('#pin').text() === thisId;
});
$rowsToGroup.each(function() {
sumVal += parseFloat($(this).find('#price').text());
$(this).remove();
});
$(this).find('#price').text(sumVal);
});
<tr class="clickable" data-toggle="collapse" id="summary_row_<%=pin%>" data-
target=".summary_row_<%= pin %>">
<td><i class="glyphicon glyphicon-plus"></i></td>
<td> <%= pin%> </td>
<td align="right"> <strong> <%= number_to_currency(amount, unit: "",
precision: 2) if amount %> </strong> </td>
</tr>
<tr id="child_row_<%=pin%>" class="collapse summary_row_<%= pin %>"
align="right" >
<td class="child_data_<%=pin%>"><strong>Year</strong></td>
<td><strong>Quarter</strong></td>
<td><strong>Amount</strong></td>
</tr>
<% if detail %>
<% detail.each do |key, value| %>
<tr id="child_row_<%=pin%>" class="collapse summary_row_<%= pin %>"
bgcolor="#fba993" align="right" >
<td class="child_data_<%=pin%>" id="pin"><%= value[0]%></td>
<td id="quart"><%= value[1]%></td>
<td id="price"><%= number_to_currency(value[2], unit: "", precision: 2) %>
</td>
</tr>
<% end %>
The code above is the Javascript code and the code below is the html/ruby code. I'm trying to make it so that when the .clickable tr class gets clicked, the function will do it's work, but it doesn't and I get this message instead:
Uncaught Error: Syntax error, unrecognized expression: .collapse.summary_row_<%= pin %>
I've noticed that the other functions in my JS files worked, but they do not have the ruby syntax inside their class names so I'm assuming that the ruby code has something to do with this error.
You're writing Rails Code inside JavaScript file, it will not work there, you have to write your rails code inside html.erb file or you can call that function inside <script> tag from html.erb file or you can use dynamic data attributes inside your html tags
If you want to use Ruby variable in your Javascript you should add erb extension to your JS file: my_file.js.erb.
Other option is to use directly my_file.coffee. Here you can change adapt your JS file JsToCoffee
Hope it helps,
I have the following code in my server.js:
app.get('/animal/:id', function (request, response)
{
Animal.find({_id: request.params.id}, function(err, animals)
{
response.render('animal', { animals: animals });
})
})
I am trying to get the animal id to show up in the template url.
<table border='1'>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
<% for (var i in animals){ %>
<tr>
<td><a href='/animal/?id=**ID RIGHT HERE** %>><%= animals[i].name %></a></td>
<td><a href='#'>Edit</a> <a href='#'>Delete</a></td>
</tr>
<% } %>
</table>
If I just put in animals[i]._id, it treats as a string, but if I write it as <%= animals[i]._id %>, the whole column is removed.
use the expression, you shouldn't send this as query.
<%= animals[i]._id %> will be used as params id in your server.js and the <%= animals[i].name %> as anchor tag name
<table border='1'>
<tr>
<th>Name</th>
<th>Actions</th>
</tr>
<% for (var i in animals){ %>
<tr>
<td><a href='/animal/<%= animals[i]._id %>'><%= animals[i].name %></a></td>
<td><a href='#'>Edit</a> <a href='#'>Delete</a></td>
</tr>
<% } %>
</table>
Can't how to deal with my problem: part of view are hidden, when page is loaded.
Here is this part:
<table>
<% #websites.each do |website| %>
<%if (current_user.id == website.user_id)%>
<tr>
<td> <%= link_to(image_tag("/images/caret-horizontal.png", id: "caret-horizontal"), '#') %> </td>
<td> <h4><%= website.name %></h4> </td>
</tr>
</table>
<table id="<%= website.id %>"> // or can be like this:
//I don't what variant is better
<table id="table-data" data-id="<%= website.id %>">>
<tr >
<td >
<%= website.url %>
</td>
</tr>
<tr>
<td >
<%= website.category %>
</td>
</tr>
<tr>
<td><%= website.language %></td>
</tr>
</table>
And I can get attributes in JavaScript like this(thanks to good people):
var yourWebsiteId = $("#table-data").attr("data-id");
How I can choose approriate element and show it? I should use getElementById or something like this, but I don't know exactly how to do it.
Please help me, if you can.
$("#table-data").show()
You can find information on this from here
$("#table-data") gets a reference to the part of the dom you are trying to access (# denotes id, . denotes class), once you have a reference you can then call any jquery operation you want on it
I am trying to write a jdo query in which I have to get a set of values based on the category that the user selects on the jsp...my query looks like this
Query query2 = pm.newQuery("select from " + ProductDB.class.getName()+ "where pCategory = " document.getElementById("cname").text);
Now on my jsp page, I have a dynamic drop-down box and in the tag I have given the id tag as "cname". So when I execute the above query I am hoping it will get the category that the user selects.
However I am getting this error:
Syntax error on token "document", delete this token
My select tag looks like this :
<select name = "cname" id="cname">
.
.
.
</select>
What am i missing here?
UPDATE :
I am putting my entire code for the jsp file below :
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# page import="java.util.*"%>
<%# page import="javax.jdo.Query"%>
<%# page import="javax.jdo.PersistenceManager"%>
<%# page import="com.google.appengine.api.users.User"%>
<%# page import="com.google.appengine.api.datastore.Key"%>
<%# page import="com.google.appengine.api.users.UserService"%>
<%# page import="com.google.appengine.api.users.UserServiceFactory"%>
<%# page import="java.net.*"%>
<%# page import="javax.servlet.http.HttpServletRequest"%>
<%# page import="com.nerdy.needs.*"%>
<html>
<head>
<title>Product Inventory</title>
<META HTTP-EQUIV="Refresh" CONTENT="450">
<link rel="stylesheet" href="login.css" type="text/css" />
</head>
<h1 align="center">Product Inventory</h1>
<body>
<form>
<table>
<tr>
<td>View</td>
<td><select name="cname" id="cname">
<option value="all">All</option>
<%
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select cname from "
+ CategoryDB.class.getName());
List<String> categories = new ArrayList<String>();
categories = (List<String>) query.execute();
String[] c = categories.toArray(new String[categories.size()]);
for (int i = 0; i < c.length; i++) {
String s = c[i];
%>
<option value="<%=s%>"><%=s%></option>
<%
}
%>
</select></td>
<td>Products</td>
</tr>
</table>
</form>
<%
if (document.getElementById("cname").value == "all") {
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery("select * from "
+ ProductDB.class.getName());
List<ProductDB> prods1 = (List<ProductDB>) query1.execute();
if (prods1.isEmpty()) {
%>
<table class="items">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<tr class="lightBlue">
<td class="actions" colspan=100%>
<p>No items were found.</p>
</td>
</tr>
</table>
<%
} else {
%>
<table class="topics">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<%
for (ProductDB p : prods1) {
%>
<tr>
<td>
<p><b> <img width="100" height="100"
src="http://localhost:8888/serve?id= <%=p.getProductImage()%>">
</b></p>
</td>
<td>
<p><b><%=p.getProductCategory()%></b></p>
</td>
<td>
<p><b><%=p.getProductName()%></b></p>
</td>
<td>
<p><b><%=p.getProductPrice()%></b></p>
</td>
<td>
<p><b><%=p.getProductDescription()%></b></p>
</td>
</tr>
<%
}
%>
</table>
<%
pm1.close();
}
} else {
PersistenceManager pm2 = PMF.get().getPersistenceManager();
Query query2 = pm.newQuery("select * from "
+ ProductDB.class.getName() + "where pCategory = "
+ document.getElementById("cname").value);
List<ProductDB> prods2 = (List<ProductDB>) query2.execute();
if (prods2.isEmpty()) {
%>
<table class="items">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<tr class="lightBlue">
<td class="actions" colspan=100%>
<p>No items were found.</p>
</td>
</tr>
</table>
<%
} else {
%>
<table class="topics">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<%
for (ProductDB p : prods2) {
%>
<tr>
<td>
<p><b> <img width="100" height="100"
src="http://localhost:8888/serve?id= %=p.getProductImage()%>">
</b></p>
</td>
<td>
<p><b><%=p.getProductCategory()%></b></p>
</td>
<td>
<p><b><%=p.getProductName()%></b></p>
</td>
<td>
<p><b><%=p.getProductPrice()%></b></p>
</td>
<td>
<p><b><%=p.getProductDescription()%></b></p>
</td>
</tr>
<%
}
%>
</table>
<%
pm2.close();
}
}
%>
</body>
</html>
I am getting "document cannot be resolved" errors in two places - one at the if statement
if(document.getElementById("cname").value=="all")
and the other at the query statement
Query query2 = pm.newQuery("select * from " + ProductDB.class.getName()+ "where pCategory = " + document.getElementById("cname").value);
Can anyone help me to figure out what is wrong?
Your concrete problem is that you're mixing Java/JSP with JavaScript. You seem to expect that they run in sync and you seem to expect that JavaScript's document object variable is also present in JSP scriptlet code.
This is wrong. Java/JSP is a HTML code generator. It runs in webserver upon a HTTP request and generates HTML/JS code and sends it back to webbrowser as HTTP response. All the webbrowser retrieves is plain HTML/JS code. Rightclick the page in webbrowser and do View Source to see it yourself.
Your concrete functional requirement seems to be that you need to grab the the submitted value of
<select name="cname">
in the Java/JSP side.
You need to get it as a request parameter by HttpServletRequest#getParameter(). So, replace
<%
if (document.getElementById("cname").value == "all") {
// ...
}
%>
by
<%
if ("all".equals(request.getParameter("cname"))) {
// ...
}
%>
That said, writing Java code in JSP files is a poor practice. Work on that as well. Note that this problem is unrelated to JDO.
You forgot the plus mark before the document.getElementById.
The correct code would be
Query query2 = pm.newQuery("select from " + ProductDB.class.getName() + "where pCategory = " + document.getElementById("cname").text);
Also, although that will fix the syntax error, the code still won't work. According to W3C DOM specification, the <select/> element doesn't have the text attribute; you should use the value, or selectedIndex in conjunction with options instead.
Try this way:-
var i = document.getElementById("cname").selectedIndex;
document.getElementById("cname").options[i].text;
OR
document.getElementById("cname").value
UPDATE:
Column names are missing too. It should be either * or specific column names.
Query query2 = pm.newQuery("select * from " + ProductDB.class.getName()+ "where pCategory = " + document.getElementById("cname").value);
As per your error update
your code should be as follows:-
if(document.getElementById("cname").value=="all")
{
<%
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery("select * from " + ProductDB.class.getName());
List<ProductDB> prods1 = (List<ProductDB>) query1.execute();
%>
}
JSP tags should be declared between tags <% and %> and other html tags should be outside.
As per your Code:
The problem is document.getElementById("cname").value calling inside the JSP tags. That is wrong.
Here either you can pass cname value as query string and get value through the parameter
OR
Assign document.getElementById("cname").value value to JSP variable and process it.
I am building a timesheet form that consists of a calendar which enables a user to select a specified date, and search for a project. I have this functionality working. What I basically have is this:
Once the user searches for their project and press the plus button, that specified project. Which in this instance is Asda the user would then click the plus icon which would create a new row and put it into the table 'task for project. How can you do this in Javascript/JQuery.
Sorry for asking what may be seen as such a basic question, but am still learning Javascript/JQuery.
I currently have the plus icon linked to project_project_tasks_path( project.id ). This is just temporary.
This is what I have so far:
<div class="left">
<table border="2" width="" id='projects' class='datatable'>
<thead>
<tr>
<th>Number  </th>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody>
<% #projects.each do |project| %>
<tr>
<td><%= project.project_number %></td>
<td><%= project.project_name %></td>
<td><%= link_to image_tag("icons/add.png"), project_project_tasks_path( project.id ), :remote => true %></td>
<!-- link_to image_tag("icons/add.png"), tasklist_path(project.id), :as => "tasklist" -->
</tr>
<%- end -%>
</tbody>
</table>
</div>
<div class="right">
<b>Recently Viewed</b>
<table>
<tr>
<th>Project No.</th>
<th>Project names</th>
<th>Project Leader</th>
<th></th>
</tr>
<tr>
<td>123</td>
<td>Test</td>
<td>1</td>
<td><%= link_to image_tag("icons/add.png") %></td>
</tr>
</table>
</div>
</fieldset>
<fieldset>
<b><center>Hours for Week commencing: <span id="startDate"><%= Date.today.beginning_of_week.strftime('%d/%m/%Y') %></span></center></b>
</fieldset>
<!-- Task list table -->
<div style="float: right; width: 300px; padding-left: 20px;">
<fieldset>
<b>Tasks for project</b>
<ul id="task_list">
</ul>
</fieldset>
</div>
<!-- Hours list table -->
<fieldset>
<table>
<tr>
<td>Leave</td>
<td><input class="dayinput" type="text" name="Leave"></td>
</t>
<tr>
<td>TOIL</td>
<td><input class="dayinput" type="text" name="TOIL"></td>
</tr>
<tr>
<td>Sick</td>
<td><input class="dayinput" type="text" name="Sick"></td>
</tr>
<tr>
<td>Total</td>
<td><input id="total" class="total_low" type="text" value="0" disabled="">
</tr>
</table>
</fieldset>
Edited:
I have created a task_list.js.erb which is as followed:
$('#task_list').html('');
<% #project.project_tasks.each do |task| %>
$('#task_list').append('<ul><%= task.task_name %>');
<% end %>
Project Controller
def index
# check if we've got a project id parameter
if( params[:project_id].nil? )
#project = nil
else
#project = Project.find(params[:project_id])
end
if #project.nil?
#project_tasks = ProjectTask.all
else
#project_tasks = Project.find(params[:project_id]).project_tasks
end
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #project_tasks }
format.js # index.js.erb
end
end
From the changes made, it outputs:
JQuery Ui autocomplete code:
$(function() {
function log(message) {
$( "<div/>" ).text( message ).prependTo("#log");
}
$("#tags").autocomplete({
source : function(request, response) {
$.ajax({
url : "/projectlist",
dataType : "json",
data : {
style : "full",
maxRows : 12,
term : request.term
},
success : function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value : item,
label : item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
});
Adding to the DOM with jQuery is very simple with the append or prepend method.
$('element_to_add_to').append('the html to append');
$('element_to_add_to').prepend('the html to append');
Check out the empty method in the jQuery docs as well.
Also, you have some bad markup. The task_list <ul> has no <li>'s and the table in there has an extra </tr>.
Edit: From your updated post, it seems like you want to not only insert a row in a table, but also save the data to your database at the same time. In that case, you'll want to make an ajax call to a controller method which will save the data in your DB. Then add the updated row to the table if the call is successful.
$.ajax({
type: "POST",
url: "path to your route",
data: "the data to send to your controller",
success: function(data){
// here is where you process the return value from your controller method
// the data variable will hold the return value if the call is successful
// you can make your controller return the html to be inserted in your table
// and insert it from here or just return a status message and build and add
// the html manually here.
}
});