I have a section on a webpage that is generated like this.
<table>
<c:forEach items="${personList}" var="person">
<tr>
<td>
</td>
<td>
<h2 style="text-align:left;">${person.reviewName}</h2>
<h2 style="text-align:right;">by ${person.name}</h2>
</td>
</tr>
<tr>
<td style="text-align:right;">
<img src="<c:url value="/resources/${person.id}.jpg" />" >
</td>
<td>
${person.review}
</td>
</tr>
<tr>
<td>
</td>
<td>
<div id="${person.id}" class="comment">comments</div>
</td>
</tr>
<tr id="ins${person.id}">
<td>
</td>
<td id="comments${person.id}" style="display:none">
<div id="ins${person.id}">
<table>
<c:forEach items="${person.comments}" var="comment">
<tr>
<td>
${comment}
</td>
</tr>
</c:forEach>
</table>
Add Comment:
<textarea id="comment${person.id}"></textarea>
<button onClick="addComment(${person.id})">add Comment</button>
</div>
</td>
</tr>
</c:forEach>
</table>
I’m trying to use JQuery.load() to instantly update the comments section when a new comment is added like this.
function addComment(id) {
$.getJSON("addComment", {id:id, comment:$("#comment" + id).val()});
$("#comments2").load("home #ins2");
}
The problem is when the when I click to add the comment it only displays the comment I previously added, meaning the comments section is always one comment behind. If I load the page directly after adding the comment it displays as it should. Another strange thing is that when I do add the comment a blank line is inserted a the top of the comments, which isn’t there/goes away when I load the page directly.
I thought this might be some kind of cache problem so tried to turn it off using
$.ajaxSetup ({
cache: false
});
However this made no difference.
I’m really at a dead end with this. Is it something to do with the section I’m pulling with load() being a forEach tag?
You need to load your comments in the
successcallback of thegetJSONmethod to wait the end of thegetJSONcall before reload yourdiv.