Search code examples
ajaxexpresspug

Reload parts of page with ajax


I am using express to show a list of running processes. I want them to reload every few seconds to remove those that are finished and add new ones.

I am using ajax for this:

My layout.pug (abridged)

div(class="processes")
    for process in processes
         div(class="process")=process.name

  script.
    setInterval(() => {
      $.ajax({
        url: "/processes/running",
        type: "GET",
        success: function(response, status, http) {
          if (response) {
              processes = $('.processes')[0]
              html = ""
              for(process of response){
                html +='<div class="process">'+process.name+'</div>'
              }
              $(processes).html(html)
          }
        }
      });
    }, 3000)

And the corresponding route is just

app.get('/processes/running', function(req, res){
    res.send(processes)
})

where processes is the array I use to keep track of them.

This works fine. However, I don't like the code duplication. I basically have to build the list/table two times in my code. If I change something, I would have to change it in both places...

So, is there some better way to accomplish this?


Solution

  • A solution to avoir duplication is simply to not initialise the inside of you div yet

    div(class="processes")
    
    
      script.
        setInterval(() => {
          $.ajax({
            url: "/processes/running",
            type: "GET",
            success: function(response, status, http) {
              if (response) {
                  processes = $('.processes')[0]
                  html = ""
                  for(process of response){
                    html +='<div class="process">'+process.name+'</div>'
                  }
                  $(processes).html(html)
              }
            }
          });
        }, 3000)
    

    The div will be populated after the first call.

    If you have already data you could put the "html creation part" (the if(response) block) in a function and call it before calling setInterval and in the response as now. This will allow you to have the code that define your array in a single place

    If you don't have yet data, I suggest to show a message in the div like "No data yet please wait"