0

I need to refresh a part of my view without refreshing the whole page.

At my index.html page I have three panels, where one shows the number of Tickets by their status, I need to refresh this number every time a new ticket is created or updated. I used Java with Spring Boot and Thymeleaf to build my application.

This is my view:

my index page

This is the way I'm doing it now:

model.addAttribute("resolvedTickets", atendimentoService.findAllTicketsByStatus(STATUS_RESOLVED).size());

I have tried to use web sockets but I can't figure out how to get this and refresh the panels.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Cisino Junior
  • 11
  • 1
  • 6

1 Answers1

0

In a standard web interaction, the client (i.e. your web browser) sends a request to your server. Your server receives the request, and sends back the information to show in your browser and then terminates the connection.

WebSockets are a way to create a persistent, two-way connection between the client and the server, but it requires cooperation from both. A lot of shared servers don't allow WebSockets, so you first have to make sure your server is capable of providing WebSockets. (I see from your screenshot that you're running on Heroku, which should have no problem running WebSockets.)

On the server side, you need to set up handling for incoming WebSocket requests. I don't know what language you've coded your server in, so I can't provide any guidance, but there are plenty of libraries that do the server-side part of WebSockets in most languages.

On the client side, you need to set up your WebSocket client. MDN has a great guide on WebSockets that explains what you'll need to do. Basically, all you'll have to do is listen for incoming messages and increment your counter.

var count = 0;
var exampleSocket = new WebSocket("ws://example.com/socket");
exampleSocket.onmessage = function(event) {
    count++;
    document.getElementById('myTicketCounter').innerHTML = count;
}

For some things, WebSockets are overkill. If you find that this is too much work for too little reward, you can also just set up an AJAX call to fire every few minutes that pings another page on your server and returns the number of tickets and updates accordingly. It won't be instantaneous, but if you don't need down-to-the-second resolution, it'll probably suffice. You can adjust the interval to be as long or as short as you want (to an extent; bombarding your server with constant requests will slow you down a bit).

Elan Hamburger
  • 2,137
  • 10
  • 14