Grammin
Grammin

Reputation: 12205

How can I update a table using ajax?

My problem is that I want whenever a new Message gets put into the messages list for it to display in the table. The problem that I'm running into is that I can't delete the old rows in the table so setInterval just keeps adding the same messages to the table every second or I can code up HornService so that it only sends new messages but then when I leave the page and come back I don't have any messages on the list because there are no messages in the list.

In my support.jsp I have:

<table id="supportMessages" class="supportTable">
<tr>
  <td class="supportColumn">
    Status  
  </td>
</tr>
</table>

<script type="text/javascript">
$(document).ready(function()
{
  setInterval(ajaxAll, 1000);
  function ajaxAll()
  {
    $.ajax
    ({
       url: "/horn/rest/main/getMessages",
       dataType: "json",
       type: "GET",
       success: function(json)
       {
         for(var i = 0; i < json.length; i++)
         {  
           $('#supportMessages tr:nth-child(1)').after(
              '<tr> <td>' + json[i].status + '</td> '+
              '</tr>');
         }
       }
    });
  }
}
</script>

And in my HornService.java I have:

static List<Message> messages = new ArrayList<Message>();

@GET
@Path("/getMessages")
public @ResponseBody List<Message> getMessages()
{
  return messages;
}

and Message.java:

public class Message
{
  private String status;
  public String getStatus()
  {
    return status;
  }

  public void setStatus(String status)
  {
    this.status = status;
  }
}

Upvotes: 1

Views: 881

Answers (1)

Grammin
Grammin

Reputation: 12205

I added this to my javascript so now it just reloads all the rows:

$.ajax
({
    url:"/horn/rest/main/getMessages",
    dataType: "json",
    type: "GET",
    success: function(json)
    {
       $("#supportMessages tr").remove();
       $('#supportMessages').prepend('<tr> ' +
             '<td class="supportColumn"> Status </td>' +
             '</tr>');

Upvotes: 1

Related Questions