Hi here i am using jquery to delete the records in the table but once I delete the record that record is coming back while updating. But if I do cancel with out doing updating that record is not coming.But the record is delete fine in the database.Can anyone plz solve my problem by seeing my code where I went wrong plz assist me.
Jquery code
$('button[id*="delid"]').click(function() {
var cnfrm = confirm("Do you really want to delete this");
if (cnfrm == true) {
var a = "trid" + $(this).val();
var tcopies = $("#abc").val();
// alert(a);
// var slno = $('#' + a).find('td:first').text();
// alert("alert" + $(this).val());
$.ajax({type: 'POST', url: 'deletebar.do?id=' + $(this).val(), success: function(result) {
if (result == 'success') {
$('#' + a).remove();
$("#abc").val(--tcopies);
$("#jkl").val(tcopies);
// $('#cancel').attr('disabled', true);
// $('#vehicletab tr').each(function() {
// var i = $(this).find('td:first').text();
// if (i > slno) {
// --i;
// }
// $(this).find('td:first').html(i);
// })
alert("Deleted Successfully", "Success");
} else {
alert("This vehicle is assigned to Route, You can't Delete it", "Error");
}
}
});
}
else {
return false;
}
});
Jsp Code
<c:forEach var="lib" items="${list}">
<table>
<tr id="trid${lib.slno}">
<td>
<label class="control-label" for="typeahead">Bar Code No :  </label>
<input type="text" name="barcode" value="${lib.getbarcode}" readonly="true"/>
</td>
<td>
<label class="control-label" for="typeahead">Accession No :  </label>
<input type="text" name="accessno" value="${lib.acession}"/>
</td>
<td>
<button type="button" id="delid${lib.slno}" value="${lib.slno}">Delete</button>
</td>
</tr>
</table>
</c:forEach>
</c:forEach>
Related
I'm posting my first question on Stack Overflow.
When I try to remove the checked data from the data table, it doesn't work.
Is there a problem with my code?
Is it right to receive data from DAO, Service, and Service Impl using Map<String,Object>commandMap?
JSP
<table id="tableDemo" class="display">
<thead>
<tr>
<th></th>
<th data-orderable="false">No.</th>
<th>그룹코드</th>
<th>그룹명</th>
<th>코드</th>
<th>코드명</th>
<th>사용여부</th>
</tr>
</thead>
<tbody>
<c:set var="count" value="1"/>
<c:forEach var="list" items="${resultlist }" varStatus="status">
<tr>
<td><input style="zoom:1.3;" type="checkbox" name="test" value=${list.codegid }></td>
<td>${count }</td>
<td>${list.codegid }</td>
<td>${list.codegnm }</td>
<td>${list.code }</td>
<td>${list.codenm }</td>
<td>${list.useat }</td>
<c:set var="count" value="${count+1}"/>
</tr>
</c:forEach>
</tbody>
</table>
<a id="delete" class="btn blue" >삭제</a>
</div>
script
$("#delete").on("click", function() {
if (confirm(" 삭제하시겠습니까?")==true) {
var cnt = $("input[name='test']:checked").length;
var ids = new Array;
$("input[name='test']:checked").each(function() {
ids.push($(this).val('id'));
});
if(cnt == 0){
alert("선택된 글이없습니다.");
}
else{
$.ajax = {
type: "POST",
url: "<c:url value='/codeDelete.do'",
data: "codegid="+ ids + "&CNT=" + cnt,
dataType: "json"
}
}
}
});
Controller
#RequestMapping(value="/codeDelete.do")
#ResponseBody
public int deleteCodes(Map<String,Object> commandMap) throws Exception{
int result=1;
try {
int cnt = Integer.parseInt((String) commandMap.get("CNT"));
String rprtOdr = (String)commandMap.get("codegid");
String [] strArray = rprtOdr.split(",");
System.out.println("list ===>>" + strArray);
for(int i=0; i<cnt; i++) {
String temp = ((String)strArray[i]);
commandMap.put("codegid", temp);
codeService.deleteCodes("codetDAO.deleteCodes", commandMap);
}
} catch (Exception e) {
log.debug(e.getMessage());
result=0;
}
return result;
}
}
serviceImpl
#Service("codeService")
public class CodeServiceImpl implements CodeService {
#Resource(name="codeDAO")
private CodeDAO codeDAO;
#Override
public void deleteCodes(String string, Map<String, Object> commandMap){
codeDAO.deleteCodes(commandMap)
}
DAO
#Repository("codeDAO")
public class CodeDAO extends EgovAbstractDAO{
public void deleteCodes(Map<String, Object> commandMap) {
delete("codeDAO.deleteCodes",commandMap);
}
SQL
<delete id="codeDAO.deleteCodes">
<![CDATA[
UPDATE codes
SET USE_AT = 'N'
WHERE codegid = #codegid#
]]>
</delete>
I am trying to delete the data by checking multiple checkboxes, but when I choose the checkboxes from the screen and hit the delete button then the only top row gets deleted. Means no matter which row I select it deletes the only first entry of the table. Please help me.
Delete.servlet
delPage = request.getParameter("delPage");
patientId = request.getParameter("pid");
if(delPage.equals("true")) {
int p = Integer.parseInt(patientId);
patientDao = new PatientDAO();
boolean b = patientDao.isPatientDeleted(p);
if (b) {
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}else
System.out.println("Patient deleting failed ... ! ");
}
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
Masterpage.jsp
<script type="text/javascript">
function addNewPatient(){
debugger;
var addNewPat = "true";
document.form.method = "POST";
document.form.action = "addPatient?newPage="+addNewPat;
document.form.submit();
}
function deletePatient(){
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}">
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
<i class="trash ulternate icon"></i>
Delete
</div>
DeletePatientServlet.java
public class DeletePatientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PatientBean patient = null;
private PatientDAO patientDao = null;
String delPage = null ;
String patientId = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
}
Okay so there are a bunch of mistakes in your code. I'll start with the jsp...
You are trying to pass parameters via the servlet url with a POST request
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
You cannot pass data in the url with post requests. You need to change your servlet to a GET if you want to do this.
Also, in this line:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
you are passing a value to your deletePatient method. But your deletePatient method does not have an option to pass a value:
function deletePatient(){ // no value being passed here?
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
You can also just do:
${user.patientId}
instead of:
<c:out value="${user.patientId}"></c:out>
Another problem with your code is this, you cannot have multiple elements in your HTML with the same id. This is illegal HTML, and it's the reason why you are getting the same id each time:
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}"> //no this is bad.
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
Your delete button is not even inside your loop, so it will not work:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)"> //this will pass the same id each time
<i class="trash ulternate icon"></i>
Delete
</div>
Try something like this instead (for delete only):
<script type="text/javascript">
function deletePatient(e){
var patientid = e.getAttribute("data-patientid");
deletePatientForm(patientid);
}
function deletePatientForm(pid) {
var form = document.createElement("form");
var input = document.createElement("input");
form.method = "POST";
form.action = "deletePatient";
input.value=pid;
input.name="pid";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>phone</th>
<th></th>
<tr>
<tr>
<td>${user.patientId}</td>
<td>${user.patientName}</td>
<td>${user.patientAddress}</td>
<td>${user.patientPhone}</td>
<td>
<div class="ui small button" onClick="deletePatient(this)" data-patientid="${user.patientId}"><i class="trash ulternate icon"></i> Delete</div>
</td>
<tr>
</c:forEach>
Then in the post of your servlet:
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
If you have any problems or questions let me know.
i am trying the example todo app,i download that example in ionic and i tried that it is working, and i trued to add another filed inside newTask.html and add in local database as same as previous value,but it is not working can you please help me how can i add another filed in the local database and get results in list html file....
NewTask.html
------------
<div class="modal" ng-controller="newTaskCtrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Add New Task</h1>
<button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
</ion-header-bar>
<ion-content>
<form ng-submit="createTask(task)">
<div class="list">
<!--label class="item item-input">
<input type="text" placeholder="Title What do you need to do?" ng-model="task.title">
</label-->
<label class="item item-input item-stacked-label">
<span class="input-label">Title</span>
<input type="text" placeholder="What do you need to do?" ng-model="task.title">
<span class="input-label">Lasr Name</span>
<input type="text" placeholder="Firstname?" ng-model="task.firstname">
</label>
<!--div class="row">
<label class="col">
<input type="" ng-model="time">
</label>
<label class="col">
<input type="text" placeholder="End?" >
</label>
</div-->
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
</ion-content>
</div>
NewTaskCtrl.js
-------------------
todoApp.controller('newTaskCtrl', function($scope, $ionicModal, $ionicPopup, SQLService) {
// Called when the form is submitted
$scope.createTask = function(task) {
SQLService.set(task.title,task.firstname);
$scope.loadTask();
$scope.taskModal.hide();
task.title = "";
task.firstname = "";
};
SQLService.js
------------------
todoApp.factory("SQLService", function ($q) {
var db;
var task='';
var deltask;
function createDB() {
try {
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
db.transaction(function(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title VARCHAR(100), firstname VARCHAR(100) )",[]);
});
} catch (err) {
alert("Error processing SQL: " + err);
}
console.log('database created');
}
function setTasks(title,firstname){
return promisedQuery("INSERT INTO tasks(title,firstname) VALUES ('" + title + "','" + firstname + "')", defaultResultHandler, defaultErrorHandler);
}
function getTasks(){
return promisedQuery('SELECT * FROM tasks', defaultResultHandler, defaultErrorHandler);
}
function defaultResultHandler(deferred) {
return function(tx, results) {
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
var t = {'id':results.rows.item(i).id,'title':results.rows.item(i).title,'firstname':results.rows.item(i).firstname};
output_results.push(t);
}
deferred.resolve(output_results);
}
}
function defaultErrorHandler(deferred) {
return function(tx, results) {
var len = 0;
var output_results = '';
deferred.resolve(output_results);
}
}
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB);
return deferred.promise;
}
return {
setup: function() {
return createDB();
},
set: function(title,firstname) {
return setTasks(title,firstname);
},
all: function() {
return getTasks();
}
}
});
PLease see the SQL Service and help me,is it correct what i add the filed name in "setTasks function.."
Ok, so you had tried the example that you had downloaded, now you have added another field in NewTask.html. But the new field that you added is not getting added to the table right??
Did you try to change the version of the DB opened??
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
to
db = window.openDatabase("todoDB", "2.0", "ToDoApp", 10*1024*1024);
I'm doing a login page with Spring MVC in server and JS & Ajax in client. I don't know what's wrong, the code of the server executes but don't return nothing.
login.html
<script type="text/javascript">
$(function() {
$(".loguser").click(function() {
var user = $("#login").val();
var pass = $("#pass").val();
$.ajax({
method: "POST",
url : "${prefix}loginUser",
data : "username=" + user + "&password=" + pass,
dataType : "json",
success: function(data){
if (data.res == "YES") alert("ok");
else alert("NOPE");
}
});
})
})
</script>
<table id="userData" class="center">
<tr id="usernametr">
<th><label for="user">Nombre de usuario: </label></th>
<th><input id="login" type="text" name="login" value=""
placeholder="Name" required /></th>
</tr>
<tr>
<th><br /></th>
</tr>
<tr>
<th><label for="pass">Clave de usuario: </label></th>
<th><input id="pass" type="password" name="pass" value=""
placeholder="Password" required /></th>
</tr>
<tr>
<th><button class="loguser">Acceder</button></th>
<th><input type="button" name="lost"
value="He perdido mi clave" /></th>
</tr>
</table>
HomeController.java:
#RequestMapping(value = "/loginUser")
#ResponseBody
#Transactional
public String loginUser(#RequestParam("username") String username,
#RequestParam("password") String pass, HttpServletRequest request, Model model) {
logger.info("Trying to log in {} {}", username, pass);
if (username.length() > 3) {
logger.info("ok");
return new String("[\"res\": \"YES\"]");
} else {
logger.warn("nope");
return new String("[\"res\": \"NOPE\"]");
}
}
I tryiend returning EntityResponse too but nothing change. Springs console prints the logger info or warn but Firefox's javascript console doesnt.
You must specify Requestmethod in controller like
#RequestMapping(value = "/loginUser", method = RequestMethod.POST)
You must Return Json Values In { }
Braces
Hi i am uploading a file using <input type="file"> in spring mvc. I submit form on change event of file and show uploaded process. But file content not uploaded and get null on server. If i upload on click of submit button every thing works fine. This is my code:
Html File:
<form:form method="POST" modelAttribute="book" id="saveBook"
name="saveBook" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Book :</td>
<td> </td>
<td>
<input type="file" name="file" id="file" class="edit_form" onchange="return upload('<c:url value='/bookstore/librery/uploadBook' />', 'saveBook', this);" />
<form:errors path="file" />
</td>
</tr>
</table>
</form:form>
Jquery Code:
function upload(requestUrl, formId, clickedObj) {
if (clickedObj && eval(clickedObj) && clickedObj != null && clickedObj != undefined) {
clickedObj.disabled = true;
}
var formData = new FormData(document.getElementById(formId));
$.ajax({
'url': requestUrl,
'type': 'POST',
'data': formData,
'cache': false,
'contentType': false,
'processData': false,
success: function (data) {
$("#tempLoc").val(data.tempLoc);
$("#bookPreview").attr("src", "data:image/png;base64," + data.image);
$("#image").val(data.image);
clickedObj.disabled = false;
},
error: function (xhr, status, err) {
clickedObj.disabled = false;
var tempErrorHTML = getAjaxRequestErrorMsg(xhr);
alert(tempErrorHTML);
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
//Do something with upload progress
alert('percentComplete = ' + percentComplete + '%');
}
}, false);
return xhr;
},
}, 'json');
}
If i call upload function on click of submit button every thing works fine. I think form is submitted before file uploaded but don't know how to make things correct.
I can't use submit function because I need to show upload progressbar. Please help.
Thanks In Advance.