Reloading data table when length of page changes - java

I have limit query on the server side which returns me data between startResult and maxResult. I want to reload data table when length of page changes.
This is my Html code:
<table class="table table-striped" id = "cardTable">
<thead>
<tr>
<th>expression</th>
<th>type</th>
<th>edit card</th>
</tr>
</thead>
<tbody>
<c:forEach var="card" items="${cards}">
<tr>
<td>${card.expression}</td>
<td>${card.type.name} <input class="card" name="card" type="hidden" value="${card.id }"></td>
<!--<td><button data-toggle="modal" data-target="#cardUpdate" class="btn btn-primary">Edit</Button></td>-->
<td><button class="updateCard btn-primary">edit</button></td>
</tr>
</c:forEach>
</tbody>
This is my controller:
#RequestMapping(value="/card.html/{startResult}/{maxResult}", method=RequestMethod.GET)
private #ResponseBody ModelAndView getCardPage(#PathVariable("startResult") int start,#PathVariable("maxResult") int maxResult) {
cards = (ArrayList<Card>) cardDao.findWithLimit(start,maxResult);
ModelAndView cardView = new ModelAndView("Card");
cardView.addObject("cards",cards);
cardView.addObject("types",types);
return cardView;
}
This is my ajax code:
function resetTable(startResult,maxResult) {
$.ajax({
type:"GET",
url: contexPath + "/card.html/" + startResult + "/" + maxResult,
data: "startResult=" + startResult + "&maxResult=" + maxResult,
success:function() {
alert("success")
},
error:function(e) {
alert('fail')
}
});
}
I have tried this
$('#cardTable').on( 'length.dt', function ( e, settings, len ) {
$("#cardTable").DataTable().clear().draw();
resetTable(0,10);
} );
})
But it has not worked. Can anyone help me please?

Related

JSP Input value To Java Method -> HttpServletRequest gives NULL value

Hello Guys.
I have simple Storage page whichs display all Products from DB.
I set to each of them with Unique name to change the Amount of product.
When i want to catch this value in Java method its returns me null.
Can you help me what i need to do to corretly catching value's in this text inputs ?
Controller :
#Controller
public class StoragePageController extends HttpServlet {
#GET
#RequestMapping(value = "/storage/subamount/{id}")
public String substractTheAmountValue(#PathVariable("id") int id, Model model, HttpServletRequest request) {
String amount_req = request.getParameter("amount_sub_" + id);
System.out.println(amount_req);
return null;
}
}
JSP fragment :
<c:set var="licznik" value="${recordStartCounter }" />
<div align="center">
<table width="1000" border="0" cellpadding="6" cellspacing="2">
<c:forEach var="u" items="${productList }">
<c:set var="licznik" value="${licznik+1}" />
<tr onmouseover="changeTrBg(this)" onmouseout="defaultTrBg(this)">
<td align="right"><c:out value="${licznik }" /></td>
<td align="left"><c:out value="${u.description }" /></td>
<td align="left"><c:out value="${u.amount }" /></td>
<td align="center"><input type="text" name="amount_sub_${licznik}" id="amount_sub_${licznik}"></td>
<td align="center"><input type="button" value="Substract the value" onclick="window.location.href='${pageContext.request.contextPath}/storage/subamount/${licznik}'"/></td>
</tr>
</c:forEach>
</table>
You should be having your API controller like the one given below given that your UI is posting the data to your API / Controller (assuming you are using the latest version of Spring Boot). You have a #Get mapping which does not accept request payload in the body.
#RestController
public class StoragePageController {
#PostMapping(value = "/storage/subamount/{id}", produces = {"application/json"})
public String substractTheAmountValue(#PathVariable("id") int id, Model model) {
String amount_req = id;
System.out.println(amount_req);
return null;
}
}

Parameter not received inside controller

I try to send a parameter applicationNo wrapped inside my form tag.The data inside input generated via javascript snippet. I need to pass this data to my controller, but it always throw null pointer exception, I am not able to figure it out what is the problem.
So kindly suggest me the best way to achieve. I also attached required source code and snapshot.
I want to send the data highlighted in red area in below screenshot.
JSP CODE:
<form action="${baseURL}view_grp_conn_applications" id="grpCreationForm" method="post" commandName="command" >
<div class="col-sm-12">
<table id="addAppTable" class="table table-responsive table-bordered table-striped text-center" id="newField">
<thead>
<tr>
<th>#</th>
<th>Application No.</th>
<th>Name</th>
<th>Mobile No.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<c:set var="i" value="0"></c:set>
<tr>
<td valign="center"><input name="workOrderPostSps[${i}]" id="workOrderPostSps[${i}]" type="checkbox" value="${wo.woPostIdEnc}" onclick="highlightrow(this);" /></td>
<td align="center"><b><input onkeypress="show_list('${i}');" id="appNo1${i}" name="applicationNo" class="form-control start" autocomplete="off" data-validate="required" required="true" placeholder="press key on keyboard"/></b></td>
<td align="left"><span id="appName1${i}"></span></td>
<td align="left"><span id="appContact${i}"></span></td>
<td align="left"><span id="email1${i}"></span></td>
</tbody>
</table>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-turquoise pull-right no-margin " name="saveBtn" id="saveBtn" value="Next >>" onclick="myfunction()">
</div>
</form>
JAVA CODE:
This method open the JSP from where I wish to send the applicationNo
#RequestMapping(value = "/create_group_connection")
public ModelAndView createConnection(Model model) {
ModelAndView mav = new ModelAndView("user/create_group_connection");
Application application = new Application();
mav.addObject("command", application);
return mav;
}
This method will open the jsp where i need to extract that applicationNo
#RequestMapping(value = "/view_grp_conn_applications", method = RequestMethod.POST)
public ModelAndView viewApplications(#ModelAttribute("command")Application application,HttpServletRequest request, HttpSession session) {
ModelAndView mav = new ModelAndView("user/grp_conn_applications");
try {
System.out.println("inside view group applications");
String[] applicationNo = request.getParameterValues("applicationNo");
System.out.println("inside " + applicationNo[0]);
// for (int i = 0; application.length > 0; i++) {
// System.out.println("application number is" + application[i]);
// }
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
return mav;
}
<td><b><input onkeypress="show_list('${i}');" id="appNo1${i}" name="applicationNo" class="form-control start" autocomplete="off" data-validate="required" required="true" placeholder="press key on keyboard"/></b></td>
you just use the below instead of above
<input type='hidden' id="applicationNo" name="applicationNo" /></b></td>
you just set the application number using Javascript through id of hidden field on any event like onBlur, onKeyPress,Your Controller code is Correct

i cannot post a specific row and get value of the fields using jQuery, i get value of first row not the submitted row

This is my jsp! i have provided an edit button to update city using ajax, i want to submit that specific row and get value of that specific row like "id &city" to update in db, i just get the value of first whether i submit the first row or some other, you help can clear my concept, Thanks in advance!
<table class="table table-responsive" style="width: 50%">
<thead>
<tr>
<th style = "text-align: center;">Id</th>
<th style = "text-align: center;">City Name</th>
<th style = "text-align: center;">Changes</th>
</tr>
</thead>
<tbody>
<c:forEach items="${CityList}" var = "ctable">
<form:form id="updatecity">
<tr>
<td id="" style = "text-align: center;">
<input type="hidden" id="id" value="${ctable.id}">
<c:out value="${ctable.id}"></c:out>
</td>
<td id="" style = "text-align: center;">
<input type="hidden" id="city" value="${ctable.city}">
<c:out value="${ctable.city}"></c:out>
</td>
<td style = "text-align: center;">
<button type="button" class="btn btn-default editbtn">Edit</button>
</td>
</tr>
</form:form>
</c:forEach>
</tbody>
</table>
This is my JQuery!
<script>
$(document).ready(function () {
$('.editbtn').click(function()
{
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function() {
return $(this).find('.editbtn').length === 0;
});
if ($this.html() === 'Edit') {
$this.html('Save');
tds.prop('contenteditable', true);
} else {
$this.html('Edit');
tds.prop('contenteditable', false);
var form = $('#updatecity');
var id = document.getElementById("id").textContent;
var city = document.getElementById("city").textContent;
var formData = "id="+id+"&city="+city;
alert(id + city);
alert(formData);
$.ajax({
url: 'updatecity',
type: 'POST',
data: formData,
success: function (data){
alert('Data submitted successfully!');
var result=data;
$('#result').attr("value",result);
},
error:function (data){
alert('There was an error to submit data');
}
});
}
});
});
</script>
You need to use unique variable names for each row (note Counter.index).
<c:forEach items="${CityList}" var = "ctable" varStatus="Counter">
<form:form id="updatecity">
<tr>
<td id="" style = "text-align: center;">
<input type="hidden" id="id${Counter.index}" value="${ctable.id}">
<c:out value="${ctable.id}"></c:out>
</td>
<td id="" style = "text-align: center;">
<input type="hidden" id="City${Counter.index}" value="${ctable.city}">
<c:out value="${ctable.city}"></c:out>
</td>
<td><button type="button"
onclick="postRow(${Counter.index})" value="Post value"></button></td>
Now you will still have to change your jS code to retrieve the selected row (selectedIndex is just the indeks(row) that is selected).
var id = document.getElementById("id"+selectedIndex).textContent;
var city = document.getElementById("city"+selectedIndex).textContent;
EDIT: I have updated my answer. You should add a button for each row and attach a click event to it that will submit the selected row.
function postRow(selectedIndex){
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function() {
return $(this).find('.editbtn').length === 0;
});
if ($this.html() === 'Edit') {
$this.html('Save');
tds.prop('contenteditable', true);
} else {
$this.html('Edit');
tds.prop('contenteditable', false);
var form = $('#updatecity');
var id = document.getElementById("id"+selectedIndex).textContent;
var city = document.getElementById("city"+selectedIndex).textContent;
var formData = "id="+id+"&city="+city;
alert(id + city);
alert(formData);
$.ajax({
url: 'updatecity',
type: 'POST',
data: formData,
success: function (data){
alert('Data submitted successfully!');
var result=data;
$('#result').attr("value",result);
},
error:function (data){
alert('There was an error to submit data');
}
});
}
}

How to Get #Transient Values in HTML

I want to get #Transient values from HTML.I had tried #Basic,it creates entry in db. I need to get this value.
Pojo:
#Transient
private int dueAmount;
public int getDueAmount() {
return dueAmount = this.getPaymentTotal() - this.getBillAmount() - this.getDiscountTotal();
}
public void setDueAmount(int dueAmount) {
this.dueAmount = dueAmount;
}
Controller
#RequestMapping(value="/billByPatientId/{id}", method = RequestMethod.GET)
public List<Bill> getBillsByPatientId(#PathVariable("id") String patientId)throws Exception {
List<Bill> BillDetailsByPatientId = billService.getBillsByPatientId(patientId);
for(Bill b : BillDetailsByPatientId){
System.out.println(b.getDueAmount());
}
return billService.getBillsByPatientId(patientId);
}
Js
$http.get('/bill/billByPatientId/'+patientData.id)
.success(function (data, status, headers, config) {
console.log(data)
$scope.bills = data;
});
HTML
<table data-ng-show='bills.length > 0' class="table table-hover">
<thead>
<tr>
<th class="col-lg-1 text-center">Bill No</th>
<th class="col-lg-3 text-center">Status</th>
</tr>
</thead>
<tr data-ng-repeat="bill in bills">
<td class="text-center">{{bill.billNo}}</td>
<td class="text-right">{{bill.dueAmount}}</td>
</tr>
In my current code i get " dueAmount " value because of printing " dueAmount " in my Controller, otherwise values will be null.
How to do this ?
I Referrer this document

from json it is not returning the result

This is jsp code what is happening is when i submit the code it will call url of ajax function and executing that function also but when returning it will call to other url
If i'm calling ajax from jsp that is going to that particular url and executing it after that it entering to the other url without returning the result
<form name="frm" action="createnewcatgoryBean.jsp" onsubmit="return validatenewcat()" method="post">
<table style="padding: 5px 0px 0px 8px;">
<tr>
<th colspan="2">
<div style="width: width:271px; color:red;" id="validate"></div>
</th>
</tr>
<tr>
<th>Category Name<span>:</span>
</th>
<td>
<input id="cat" onblur="return validatenewcat()" type="text" name="category">
</td>
</tr>
<tr>
<th>Quotations form<span>:</span>
</th>
<td>
<input type="checkbox" name="quotations">
</td>
</tr>
<tr>
<th>Agreement form<span>:</span>
</th>
<td>
<input type="checkbox" name="agreement">
</td>
</tr>
<tr>
<th>Payment form<span>:</span>
</th>
<td>
<input type="checkbox" name="payment">
</td>
</tr>
<tr>
<th>ETI<span>:</span>
</th>
<td>
<input type="checkbox" name="eti">
</td>
</tr>
<tr>
<td colspan="2" style="float:right; padding-top:15px">
<input type="submit" value="Submit" style="width: 60px;">
</td>
</tr>
</table>
</form>
This is the JavaScript code that includes the AJAX request:
function validatenewcat() {
var category = document.getElementById("cat").value;
if (category == "") {
setTimeout(document.getElementById("validate").innerHTML = "!PLz Enter The Category Name", 2000);
return false;
} else {
var url = "catnamecheck.do?id=" + category;
xmlhttp.open("post", url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var temp = xmlhttp.responceText;
obj = JSON.parse(temp);
alert(obj);
if (temp != "") {
document.getElementById("validate").innerHTML = "!PLz Enter The Unique Category Name";
document.getElementById("cat").focus();
return false;
}
}
}
}
}
}
this my java code
public Map<String, String> catuniqecheck(String id) {
Connection c = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
String sql=null;
try{
c = JDBCHelper.getConnection();
if(c!=null)
{
Map<String, String> map = new HashMap<String, String>();
sql="select * from catgory where catgoryname=?";
ps1=c.prepareStatement(sql);
ps1.setString(1, id);
ps1.execute();
rs1=ps1.getResultSet();
if(rs1.next())
{
System.out.println("insdide of the catuniqecheck");
map.put("catgoryname",rs1.getString("catgoryname"));
}
return map;
}
else
{
System.out.println("DB connection Established");
return null ;
}
}
catch (Exception e) {
// TODO: handle exception
return null ;
}
finally{
JDBCHelper.close(rs1);
JDBCHelper.close(ps1);
JDBCHelper.close(c);
}
}
this my servlet code
Map<String, String> result =p1.catuniqecheck(id);
if(result!=null)
{
System.out.println("inside success");
JSONObject json = new JSONObject();
json.accumulateAll(result);
System.out.println("inside json"+json.toString());
response.setContentType("application/json");
response.getWriter().write(json.toString());
}
try with
obj = JSON.parse("["+temp+"]")
And then first response length
alert(obj[0].length);
alert(obj[0]);
bcoz sometime response itself inside Square brackets like [{...}]

Categories

Resources