'Error in getting table row value to be deleted/updated. String input as undefined
I am making a simple CRUD function for a bill management system. It uses Jquery AJAX JSON to communicate to the servlets.
The update and delete functions are activated by buttons in a dynamically generated table with hidden field that contains the 'billID'.
However when tested it gives an error For input String : "undefined". I think the error should be in billid hidden field somehow not been set? But I'm not sure and would like a bit of help.
.jsp HTML table.
<form id="formBill" name="formBill">
UserID : <input id="UserID" name="UserID" type="text" class= "form-control form-control-sm" required> <br>
Billing Date (yyyy-mm-dd): <input id="BillingDate" name="BillingDate" type="text" class= "form-control form-control-sm" required> <br>
Unit Cost : <input id="UnitCost" name="UnitCost" type="text" class="form-control form-control-sm" required> <br>
Units Used : <input id="UnitsUsed" name="UnitsUsed" type="text" class="form-control form-control-sm" required> <br>
Service Charge : <input id="ServiceCharge" name="ServiceCharge" type="text" class="form-control form-control-sm" required> <br>
Bill Settled : <select id="BillSettled" name="BillSettled" required>
<option value="false">False</option>
<option value="true">True</option>
</select>
<br><br><br>
<input id="btnSave" name="btnSave" type="button" value="Save" class="btn btn-primary">
<input type="hidden" id="hidBillIDSave" name="hidBillIDSave" value="">
</form>
<br>
<div id="alertSuccess" class="alert alert-success"></div>
<div id="alertError" class="alert alert-danger"></div>
<br>
<div id="divItemsGrid">
</div>
The dynamically generated table is placed in the divItemsGrid div.
Here are the Jquery ajax code
// Save =================================================
$(document).on("click", "#btnSave", function(event) {
// Clear alerts---------------------
$("#alertSuccess").text("");
$("#alertSuccess").hide();
$("#alertError").text("");
$("#alertError").hide();
// Form validation-------------------
var status = validateBillForm();
if (status != true) {
$("#alertError").text(status);
$("#alertError").show();
return;
}
//var type = ($("#hidItemIDSave").val() == "") ? "POST" : "PUT";
var type;
if ($("#hidBillIDSave").val() == ""){
type = "POST";
}
else{
type = "PUT";
}
$.ajax(
{
url: "BillsAPI",
type: type,
data: $("#formBill").serialize(),
dataType: "text",
error: function(response, status, error) {
console.log(response);
},
complete: function(response, status)
{
onBillSaveComplete(response.responseText, status);
}
});
});
// UPDATE==========================================
$(document).on("click", ".btnUpdate", function(event) {
$("#hidBillIDSave").val($(this).data("billID"));
$("#UserID").val($(this).closest("tr").find('td:eq(0)').text());
$("#BillingDate").val($(this).closest("tr").find('td:eq(1)').text());
$("#UnitCost").val($(this).closest("tr").find('td:eq(2)').text());
$("#UnitsUsed").val($(this).closest("tr").find('td:eq(3)').text());
$("#ServiceCharge").val($(this).closest("tr").find('td:eq(4)').text());
$("#BillSettled").val($(this).closest("tr").find('td:eq(5)').text());
});
// DELETE==============================================
$(document).on("click", ".btnRemove", function(event) {
$.ajax(
{
url: "BillsAPI",
type: "DELETE",
data: "billID=" + $(this).data("billID"),
dataType: "text",
complete: function(response, status) {
onBillDeleteComplete(response.responseText, status);
}
});
});
The update function sets the values into the form. If there is a hidden value then we use PUT to update the table. If not it becomes a POST.
I believe the error is here. Somehow the hidden billID value must not be getting set.
Below are the CRUD functions. They are a bit long but the dynamically generated table is in the read function.
//Create Bills
public String createBill(String BillingDate, String unitCost, String unitsUsed, String serviceCharge, String billSettled, String userID) {
String output = "";
try {
Connection con = connect();
if(con == null) {
return "Error while connecting to the database for inserting.";
}
//calculate total cost
int totalCost = (Integer.parseInt(unitCost) * Integer.parseInt(unitsUsed)) + Integer.parseInt(serviceCharge);
//create a prepared statement
String query = "insert into bills (`billDate`, `unitCost`, `unitsUsed`, `serviceCharge`, `totalCost`, `settled`, `userID`)"
+" values(?,?,?,?,?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
//converting String to util.Date to sql.Date
java.util.Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(BillingDate);
java.sql.Date date2 = new java.sql.Date(date1.getTime());
// binding values
preparedStmt.setDate(1, date2);
preparedStmt.setInt(2, Integer.parseInt(unitCost));
preparedStmt.setInt(3, Integer.parseInt(unitsUsed));
preparedStmt.setInt(4, Integer.parseInt(serviceCharge));
preparedStmt.setInt(5, totalCost);
preparedStmt.setBoolean(6, Boolean.parseBoolean(billSettled));
preparedStmt.setInt(7, Integer.parseInt(userID));
// execute the statement
preparedStmt.execute();
con.close();
//output = "Inserted successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while inserting the item.";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
//Update Bills
//for settles bills
public String updateSettledBills(String billID, String billSettled) {
String output = "";
Connection con = connect();
try {
if(con == null) {
return "Error while connecting to the database for updating.";
}
//create prepared statement
String query = "update bills set settled=? where billID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
//binding values
preparedStmt.setBoolean(1, Boolean.parseBoolean(billSettled));
preparedStmt.setInt(2, Integer.parseInt(billID));
//execute statement
preparedStmt.execute();
con.close();
//output = "Updated successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while updating bill";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
//Delete Bills
public String deleteBill(String billID) {
String output = "";
try {
Connection con = connect();
if(con == null) {
return "Error while connecting to the database for deleting.";
}
//create prepared statement
String query = "delete from bills where billID=?";
PreparedStatement preparedStmt = con.prepareStatement(query);
// binding values to prepared statement
preparedStmt.setInt(1, Integer.parseInt(billID));
// execute the statement
preparedStmt.execute();
con.close();
//output = "Deleted successfully";
String newBills = readBills();
output = "{\"status\":\"success\", \"data\": \"" + newBills + "\"}";
}
catch(Exception e) {
//output = "Error while deleting the bill.";
output = "{\"status\":\"error\", \"data\": \"Error while inserting the item.\"}";
System.err.println(e.getMessage());
}
return output;
}
Finally, here are the servlets.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String output = billObj.createBill(
request.getParameter("BillingDate"),
request.getParameter("UnitCost"),
request.getParameter("UnitsUsed"),
request.getParameter("ServiceCharge"),
request.getParameter("BillSettled"),
request.getParameter("UserID"));
response.getWriter().write(output);
}
// Convert request parameters to a Map
private static Map getParasMap(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
try {
Scanner scanner = new Scanner(request.getInputStream(), "UTF-8");
String queryString = scanner.hasNext() ? scanner.useDelimiter("\\A").next() : "";
scanner.close();
String[] params = queryString.split("&");
for (String param : params) {
String[] p = param.split("=");
map.put(p[0], p[1]);
}
} catch (Exception e) {
}
return map;
}
/**
* @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
*/
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paras = getParasMap(request);
//System.out.println(paras.get("billID").toString());
String output = billObj.updateSettledBills(
paras.get("billID").toString(),
paras.get("BillSettled").toString());
response.getWriter().write(output);
}
/**
* @see HttpServlet#doDelete(HttpServletRequest, HttpServletResponse)
*/
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map paras = getParasMap(request);
String output = billObj.deleteBill(paras.get("billID").toString());
response.getWriter().write(output);
}
Sorry for the bloated post. I would greatly appreciate some with regards to this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|