Marius-Cristian Dragan Marius-Cristian Dragan - 4 months ago 14
Ajax Question

Edit table and save modification to database

In my JSP I populate the table as follows(only relevant data):

<c:forEach var="person" items="${personsList}">
<c:forEach var="account" items="${person.accounts}">
<tr>
<td>${account.accountId}</td>
<td contenteditable='true' onblur="saveData(${person.id},${account.accountId},${account.balance})">${account.balance}</td>
</c:forEach>
</c:forEach>


Please note that I wanna use "onblur" event.
My JavaScript looks like this:

function saveData(id, accId, balance) {
$.ajax({
type : "POST",
url : "updateBalance.html",
data: ({id : id, accId : accId, balance : balance}),
success : function(data) {
if (data!="success!!") {alert("done")}
else {alert("error!!")}
}
})
}


The problem is that I don't know how to send the new "balance" value(when I'm calling the javascript function, I always send the balance loaded when page was first time loaded).

JPG JPG
Answer

You can pass this object to your javascript function saveData like this:

<c:forEach var="person" items="${personsList}">
    <c:forEach var="account" items="${person.accounts}">
    <tr>                   
    <td>${account.accountId}</td>
    <td contenteditable='true' onblur="saveData(this, ${person.id},${account.accountId},${account.balance})">${account.balance}</td>
    </c:forEach>
</c:forEach>

And redefine your function like this:

function saveData(obj, id, accId, balance) {
    $.ajax({
        type : "POST",
        url : "updateBalance.html",
        data: ({id : id, accId : accId, balance : $(obj).text()}),
        success : function(data) {
            if (data!="success!!") {alert("done")}
            else {alert("error!!")}
        }
    })
}