DataTables spring mvc support
I am using one Weblogic data source, I am ultimately attempting to retrieve one record at a time from the Weblogic data source and then display that record in a data table also one at a time. DataTables.net has an example called "add rows" but it does not accommodate using getting data from data sources. The empty data table displays on the webpage, I can see the query running correctly to the data source however the record is not displaying in the data table.
I included the following in my code:
<script src="<c:url value="/resources/js/jquery.js" />"></script>
<script src="<c:url value="/resources/js/jquery.min.js" />"></script>
<script src="<c:url value="/resources/js/jquery.dataTables.min.js" />"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css"/>
Snippet from CONTROLLER:
#RequestMapping(value = "/locate", method = RequestMethod.GET)
public #ResponseBody NewOrder getModelYearAndVehicleOrder(
#RequestParam(value="modelYear") String modelYear\,
#RequestParam(value="vehicleOrder\") String vehicleOrder\){
if (modelYear\.isEmpty() || vehicleOrder\.isEmpty())
throw new IllegalArgumentException("Try Again!");
NewOrder newOrder;
try {
newOrder= OrderRepo.findNewOrderByModelYearAndVehicleOrder(modelYear, vehicleOrder);
}
catch (Exception e){
#SuppressWarnings("deprecation")
Throwable _e = ExceptionUtils.getCause(e);
throw new ExceptionHandler(
DatabaseMessage.RETRIEVE_ERROR.toString(), _e.getMessage());
}
return newOrder;
}
HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body>
<h1>Template Spring MVC App</h1>
<form id= "locateVehicle">
<p> Model Year? <input id="modelYear" type="text" th:field="*{modelYear}" /> </p>
<p> Order? <input id="orderNum" type="text" th:field="*{vehicleOrder}" /> </p>
<button onclick="goToDetails()">Locate</button>
</form>
<br></br>
<div class="row">
<div class="col-lg-12">
<table id="list" class="display">
<thead>
<tr>
<th>Model Year</th>
<th>Order #</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<c:forEach var="order" items="${order}" varStatus="loop">
<tr>
<td><c:out value="${order.modelYearNbr}" /></td>
<td><c:out value="${order.vehicleOrderNm}" /></td>
<td><c:out value="${order.model}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
JS:
<script>
$(document).ready( function () {
$('#list').DataTable();
} );
function goToODetails() {
var modelYear = $('#modelYearId').val();
var vehicleOrder = $('#vehicleOrderId').val();
var url = './DataLoader/locate?modelYear=' + modelYear + '&vehicleOrder' + vehicleOrder;
$.get(url,function(result) {
var vehicle = result;
var list = $("#list");
list.append('<tr><td>' + result.modelYearNbr + '</td>' +
'<td>' + result.vehicleOrderNm + '</td>' +
'<td>' + result.model + '</td></tr>');
});
}
</script>
Before I added the data table files I was able to see the record post to the webpage, now it is not posting to the table.
Finally got it working, here is how:
$(document).ready(function() {
var table = $('#orderList').DataTable()
$('#goToOrder').on('click', function() {
var modelYear = $('#modelYearId').val();
var url = './DataLoader/locate?modelYear=' + modelYear;
$.get(url, function(result) {
$(result).each(function( i, object ){
var vehicle = result[i];
table.row.add([
vehicle.modelYear,
vehicle.vehicleOrder,
vehicle.model
]).draw(false)
.nodes()
.to$();
})
})
})
});
Related
Based on my question, I have a table that displays all data from a JSON link. Each row will have a view button that will display the details of the data. The details will display at the next page. I use input hidden using form to send the row id to the next page. But, no id display at the next page after i click button "view". Below is the example of my code:
index.html
<div >
<table id="mypanel">
<tr>
<th>Report ID</th>
<th>Task Name</th>
<th>Report</th>
<th>Action</th>
</tr>
</table>
</div>
<script>
$.getJSON('https://testing.com/testing.asmx/ot_displayTask?badgeid=10010079&reportStatus=&status=yes', function(data) {
$.each(data.otReportList, function(key, data){
// console.log(key, data);
let current_datetime = new Date(data["report_date"])
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getFullYear()
var text = `<tr>
<td>${data["report_id"]}</td>
<td>${data["task_name"]}</td>
<td>${formatted_date}</td>
<td>
<form method="POST" action="read.html">
<input type="hidden" name="report_id" id="report_id" value="${data["report_id"]}">
<button type="submit">View</button>
</form>
</td>
</tr>`
$("#mypanel").append(text);
})
});
</script>
read.html
<html>
<head>
</head>
<body>
<h2>Input 1: <span id='result1'></span></h2>
</body>
</html>
<script>
window.addEventListener('load',() =>{
const params = (new URL(document.location)).searchParams;
const report_id = params.get('report_id');
document.getElementById('result1').innerHTML=report_id;
})
</script>
Can anyone know how to solve it?
You need to change method to GET so that the report id data come as querystring.
<form method="GET" action="read.html">
<input type="hidden" name="report_id" id="report_id" value="${data["report_id"]}">
<button type="submit">View</button>
</form>
Then in your read.html -> JS:-
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]});
console.log(queryDict.report_id);
Above location querystring is from How can I get query string values in JavaScript?
I need help in passing the values present in the jquery function of a jsp page to a servlet.
I have grouped the set of values present in the checked check box row using the jquery function.Now I need to insert those values into my database. I tried to pass the values using request.getParameterValues(),but it is not working. Kindly help me in passing the stored array values present in the jquery function of my jsp page to the servlet.
This is my jquery function present in the jsp page
<script>
$('#btn').on('click', function() {
var checkedRows = [];
$(':checkbox:checked').closest('tr').each(function() {
checkedRows.push(
$(this).find('td:gt(0)').map(function() {
return $(this).html();
}).get()
);
});
console.log( checkedRows );
});
</script>
JSP page
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script>
$('#btn').on('click', function() {
var checkedRows = [];
$(':checkbox:checked').closest('tr').each(function() {
checkedRows.push(
$(this).find('td:gt(0)').map(function() {
return $(this).html();
}).get()
);
});
console.log( checkedRows );
});
</script>
</head>
<form name="sform" method="post" action="Save_Products">
<table style="width:40%">
<tr> <th> Brand Name</th>
<th> Product Name</th>
<th> Description</th>
</tr>
<tr>
<td><%
List<Products> pdts = (List<Products>) request.getAttribute("productlist");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"hidden\" name=\"brand_name\" value=\"" + prod.getBrandname() + "\">");
out.println("<br/>"+prod.getBrandname());
} %> </td>
<td><%
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" checked=\"checked\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} } %> </td>
<td><%
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\" value=\""+prod.getDesc()+"\"/><br/>");
}
}
} %> </td>
</tr>
<br/>
<br/>
<tr>
<td></td>
<td align="center"> <input id="btn" type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</html>
try this code for passing js array to servlet :
in your jsp add :
$.post('Save_Products', {arrayData:checkedRows, mode:"insert"});
In your servlet :
String[] arrayData=request.getParameterValues("arrayData[]");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Javascript Array Table</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<meta name="" content="">
</head>
<body>
<table>
<thead>
<tr>
<th>Details</th>
<th>Data</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
<script type="text/javascript">
//jQuery( document ).ready(function() {
function arrayprocess(){
var display;
var arrayobj = [{"name": "John","dept": "science","phone": "xxx-xxx-xxxx"}];
jQuery.each(arrayobj, function(key, value){
jQuery.each(value, function(label, answer){
display = '<tr><td>'+label+ '</td><td>' +answer+'</td></tr>'});
});
$('#tbody').append(display);
}
arrayprocess();
//});
</script>
</body>
</html>
Problem:
The JSON only array's last value is displayed. The rest of previous two values that is, name:John and dept:science...
Present output:
Details Data
phone xxx-xxx-xxxx
Expected Output
Details Data
Name John
dept science
phone xxx-xxx-xxxx
Your append statement needs to be inside the each function or else it will only append the last result, ex:
jQuery.each(arrayobj, function(key, value){
jQuery.each(value, function(label, answer){
display += '<tr><td>'+label+ '</td><td>' +answer+'</td></tr>';
});
});
why does phone gap changes error after every-time it is compiled.
some times it runs without any error and then the same code gives silly errors such parse error of function not found despite no changes made to the code.
here is the code which gives different errors at each compile
<html>
<head>
<link href="index.css" rel="stylesheet" type="text/css">
<link href="wrapper.css" rel="stylesheet" type="text/css">
<link href="natiweb.css" rel="stylesheet" type="text/css">
<script type="text/javascript" charset="utf-8" src="cordova-2.3.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" charset="utf-8">
function loadcontact()
{
alert('load');
// navigator.contacts.find("*",contactSuccess, contactError);
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="Bob";
options.multiple=true;
var fields = ["displayName", "name"];
**navigator.contacts.find(fields, contactSuccess onError, options);**
window.location = "download.html";
}
function contactSuccess(contacts)
{
alert('success');
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
}
}
function contactError(error)
{
alert('error');
}
</script>
</head>
<body class="index">
<p></p>
<h1 class="natiweb">NatiWeb</h1>
<form name ="choicepage" id="wrapper" >
<table id="wrapper" >
<tr><td>
<table align="center">
<tr></tr>
<p><b>Select Upload/Download</b></p>
<select name="upload/download">
<option selected >Upload</option>
<option>Download</option>
</select>
</td>
</tr>
<tr>
<td><img src="images/contact-icon.png" height="15"> Contacts </td>
<td><input name="opt" type="checkbox" value="Contacts"></td>
</tr>
<tr>
<td><input type="button" value="Back"></td>
<td><input type="submit" value="Next1" onclick="loadcontact();"></td>
</tr>
</table>
</table>
</form>
</body>
</html>
errors 1:SyntaxError: Parse error at file:///android_asset/www/choice.html:22 here line 22 is marked in bold
You have comma missing on that line.
One more thing, you should redirect the user after you receive the success/error callback, not before.
function loadcontact()
{
alert('load');
// navigator.contacts.find("*",contactSuccess, contactError);
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="Bob";
options.multiple=true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, contactSuccess, onError, options);
}
function contactSuccess(contacts)
{
alert('success');
for (var i=0; i<contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
}
window.location = "download.html";
}
function contactError(error)
{
alert('error');
window.location = "download.html";
}
I have a table with dynamically changing rows items.
Among the rows there is a small button / link for each unit.
Eg
Data1 | LinkButton
Data2 | LinkButton
Data3 | LinkButton
Data4 | LinkButton
Data5 | LinkButton
Data6 | LinkButton
What i want is that when i click on the link button ,i need to know which row is selected?Can any one give me pointers on how that can be done?
You help will be greatly appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
</head>
<body><center>
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form action="" id="searchForm">
<label for="search">Matter Search:</label> <input type="text" name="search" id="search" />
<input type="submit" id="submit" value="Submit" />
Link
</form>
<div id="matterTableDiv" style="display: none;">
List of Matters
<table id="matterTable" border="1">
<thead>
<th>Matter Names</th>
<th>Matter Number</th>
<th>Description</th>
<th></th>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="matterDetailTableDiv" style="display: none;">
Matter Detail Table
</div>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search').focus();
$('#submit').click(function(){
$('#message').hide(200);
$("#matterTableDiv").hide(200);
$("#matterTable tbody").text("");
$('#waiting').show(200);
$('#searchForm').hide(200);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
search : $('#search').val()
},
success : function(data){
if(data.msg == "[]" ){
$('#waiting').hide(200);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(200);
$('#searchForm').show(200);
}
$('#waiting').hide(200);
$('#matterTableDiv').removeClass().addClass((data.error === true) ? 'error' : 'success')
if(data.error == false){
var str = JSON.parse(data.msg);
$("#matterTableDiv").show(200);
//alert("List :" + str.length);
//alert("List :" + str.toString());
$("#matterTable").html();
$.each(str, function(key, value) {
var tblRow =
"<tr>"
//+"<td><a id="+key+" href='#dbID="+value.dbID+"&matID="+value.matterID+">"+value.matterInfoSortName+"</a></td>"
+"<td>"+value.matterInfoSortName+"</td>"
+"<td>"+value.matterInfoMatterNum+"</td>"
+"<td>"+value.matterInfoFileDesc+"</td>"
+"<td><input type='button' value="+value.matterInfoFileDesc+"></td>"
+"</tr>";
$(tblRow).appendTo("#matterTable tbody");
//alert(key + ': ' + value.matterInfoSortName);
});
$("button").live("click",function(){
var row = $(this).closest("tr");
var rowIndex = row.index();
alert(rowIndex);
});
}else{
$('#message').removeClass().addClass('error')
.text('There was an error.').show(200);
}
$('#searchForm').show(200);
if (data.error === true)
$('#searchForm').hide(200);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(200);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(200);
$('#searchForm').show(200);
}
});
return false;
});
});
</script>
</center>
</body>
I know that you ask for the row index, there are users that have given you the answer.
But, usually we need the id of the row, because the id belongs to an id in the database.
In this case, you could use the id of the cell or the button itself.
Example:
<table>
<tr id="Data1"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
<tr id="Data2"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
<tr id="Data3"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
<tr id="Data4"><td>a</td><td>b</td><td>c</td><td><input type="button" value="Data"/></td></tr>
</table>
$("input[type=button]").live("click", function() {
var row = $(this).closest("tr");
var rowId = row.attr("id");
alert(rowId);
});
You have this here:
http://www.jsfiddle.net/dactivo/YD3xy/
You can go from this (the clicked button) in the handler and use .closest() to get the <tr> of the button then grab anything you want from there, for example:
$(".someButton").live("click", function() {
var row = $(this).closest("tr");
var rowIndex = row.index();
});
For a full list of "moving-around" functions like this, check out the Tree Traversal section of the API.
I am guessing you are using...
$('.all_links').click(some_function)
So in that case, you can simply find it from inside some_function like so:
function some_function() {
$(this).parents('tr'); // this will give you the link's row.
}