Update the HTML table using Jquery and PHP

Asked

Viewed 114 times

-1

I’m still new to this area of Web programming, I’m managing here,

I have a code that performs the ping test of some hosts and returns whether they are online or not. However I saw in another code I found on the Web that it is possible to update an individual row in the table and uses a spinner to show that the line is being updated.

<?php
$title = "Monitora"; // website's title
$servers = array(

  'HOST 1' => array(
    'ip' => '10.65.1.1',
    'info' => 'HOST 1',
  ),
  'HOST 2' => array(
    'ip' => '10.65.2.2',
    'info' => 'HOST 2',
  ),
  'HOST 3' => array(
    'ip' => '10.65.3.3',
    'info' => 'HOST 3',
  ),
)
?>
<!doctype html>
<html lang="en">

<head>
  <style>

  </style>
  <meta charset="UTF-8">
  <title><?php echo $title; ?></title>
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/2.3.2/cosmo/bootstrap.min.css">
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
  <style type="text/css">
    /* Custom Styles */
  </style>
</head>

<body>

  <div class="container">
    <h1><?php echo $title; ?></h1>
    <table class="table">
      <thead>
        <tr>
          <th></th>
          <th>Nome</th>
          <th>Host</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($servers as $name => $server) :

          $ip =    $server['info'];
          exec("ping -n 2 $ip", $output, $status);


          if ($status == 0) {
            $status_ping = "success";
          } else {
            $status_ping = "error";
          }


        ?>
          <tr class="<?php echo $status_ping ?>">
            <td><i class="icon-spinner icon-spin icon-large"></i></td>
            <td class="name"><?php echo $name; ?></td>
            <td><?php echo $server['info']; ?></td>
            <td><?php echo $status_ping ?>
          </tr>

        <?php endforeach; ?>

      </tbody>
    </table>
  </div>



</body>

</html>

Exemplo do spinner rodando enquanto atualiza a linha que esta offilne

  • 1

    And what is the doubt?

  • @Franklinbarreto I don’t know how to update the table row individually...

  • You are only ping once when the page is loaded. there is no way to update just one row ai. You will just double check by refreshing the page again. you can for example separate the php check from the front and make an ajax request to register 5 seconds for all rows of the table that are still pending

  • Tries to put an id on the lines you need to update, the logic is the same.

2 answers

1

Your question is not so clear, but I did something similar, it is not so dynamic, but it works!

$(function() {
// dados armazenados como objeto (opcional, podes obter através de API)
    var hosts = {'Host1': '10.65.2.2',
        'Host2': '10.65.1.1', 
        'Host3': '127.0.0.1', 
        'Host4': '10.65.3.3'}; 

    Object.entries(hosts).forEach(([name, host]) => {
        checkHost(name, host);
    });
});

function checkHost(name, host) {
    fetch(`check.php?host=${host}`, {method:'get', mode:'cors'}).then(res => res.json())
        .then((j) => {
            $('tbody').append(`<tr id="${name}" class="${j.class}">
                <td><i class="icon-spinner icon-spin icon-large"></i></td>
                <td>${name}</td>
                <td>${j.host}</td>
                <td>${j.status} (${j.ping})</td>
                <td><a href="javascript:void(0)" onclick="return checkHost('${name}', '${j.host}');">Verificar</a></td>
            `);
        });
}
body, html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
<!DOCTYPE html>
<html>
<head>
    <title>Monitora</title>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootswatch/2.3.2/cosmo/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>Monitora</h1>
        <table class="table">
            <thead>
                <tr>
                    <th></th>
                    <th>Nome</th>
                    <th>Host</th>
                    <th>Status</th>
                    <th></th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</body>
</html>

check php.

<?php  
    
    error_reporting(0);

    if (($_GET['host'])) {
        exec("ping -n 2 {$_GET['host']}", $output, $status);
            // obtem o valor da Média fornecido pelo comando ping usando regex
            preg_match_all("/= ([0-9ms]+)/", $output[9], $matches, PREG_SET_ORDER);

            // imprime um objeto json para voltar como response no fetch.
            print_r(json_encode(array(
                'host' => $_GET['host'],
                'status' => $status == 0 ? 'Sucesso' : 'Erro',
                'class' => $status == 0 ? 'success' : 'error',
                'ping' => trim($matches[2][1]) == '' ? '0ms' : trim($matches[2][1])
            ))); 
    }

It stayed this way, as shown in the image below

inserir a descrição da imagem aqui

I hope you helped him! Good studies :)

0

Good afternoon.

Look, I had a problem similar to yours a while back, in case I had a div with ID = ping, and inside that div I was using the code below:

exec('ping -n 1 google.com',$available, $return); if ($return == 0) { echo ''; echo '

OK

'; } Else { echo 'Down'; }

And I needed to update it so that it was dripping he would create a div with id ok and with the green or red background if it wasn’t dripping, then to update only the div ping which is where the php code was I used this code in javascript/jquery:

Citation $(Document). ready(Function(){ setInterval(Function(){ $("#ping"). load(window.location.href + "#ping"); }, 1000); });

I hope it’s useful to you.

  • In case I can update the table line or could I just get through a div? I did it with div and it worked, but I needed to update the table rows individually

  • Diogo, sorry, I think I did not know how to express myself well in my last answer and dropped her rsrs, but then I would try to do it this way:(Document). ready(Function(){ setInterval(Function(){ $(". table"). load(window.location.href + ". table"); }, 1000); });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.