How to display the contents of a div with PHP parameters

Asked

Viewed 306 times

0

I need help updating content within a div that is displayed as a result in PHP.

This div contains PHP variables to display the results that are taken from a text file that is in another directory. You can give an auto refresh in a few seconds (even if it is in script or Ajax, but it needs to receive a PHP parameter so that the auto refresh stops when the php function is finished running) ?

This is the content it contains in Div:

<div class="results">
  <?php
    //abrimos o arquivo em leitura
    $arquivo = 'log/speedtest.txt';
    $fp = fopen($arquivo, 'r');

    //lemos o arquivo
    $texto = fread($fp, filesize($arquivo));

    //transformamos as quebras de linha em etiquetas <br>
    $texto = nl2br($texto);

    echo $texto;
  ?>
</div>

And this is the function that is performed by sending the form:

<?php

    if(isset( $_POST['submit'] )) {
        if( $_POST['ntestes'] == "0" ) {
            echo "<script type='text/javascript'>alert('Último teste realizado.')</script>";
        }
        if($_POST['ntestes'] >= "1" ) {
            echo "<script type='text/javascript'>alert('Testes realizados com sucesso!')</script>";
        }

        $ntestes = escapeshellarg($_POST["ntestes"]);

        $teste = shell_exec('/bin/speedtest ' .$ntestes. ' -l printf $?');

    }

?>

This is the form that receives the values for executing the php function above:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" class="form">
  <p>
    <label>Número de testes: </label>
  </p>
  <select name="ntestes">
    <option value="0">0</option>
    <option value="1"selected>1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
  </select>
  <input type="submit" name="submit" class="execute" value="Executar">
  <a href="log/" class="btn" target="_blank">Visualizar Logs</a>
</form>

Any idea how I can do that ?

  • To div is on the page log/?

  • @Andreicoelho No, this log/ is another page to display logs only.

  • Is everything on the same page? All these codes?

  • @Andreicoelho Yes, all the code posted on the question is from the same page.

  • And you want the div "Results" to keep updating, using that php code that’s inside it, that’s it?

  • This, but it has to stop when the php function is finished running.

  • Stop her when the ntestes is equal to 0. Is that it? You have to stop when you finish running Speedtest

  • In the case when the variable $teste is equal to 0 so I put the remote shell_exec within a variable. This variable will receive the value as a parameter of the executed function.

Show 4 more comments

1 answer

1


According to the conversations we had, I created a script that should work. But first it will be necessary to create 2 files in the same directory of index1.php:

1 - shell_test.php

if(isset( $_POST['submit'] )) {

    $ntestes = escapeshellarg($_POST["ntestes"]);

    $teste = shell_exec('/bin/speedtest ' .$ntestes. ' -l printf $?');

}

I removed the ifBecause I didn’t understand their need.

2 - result_list.php

//abrimos o arquivo em leitura
$arquivo = 'log/speedtest.txt';
$fp = fopen($arquivo, 'r');

//lemos o arquivo
$texto = fread($fp, filesize($arquivo));

//transformamos as quebras de linha em etiquetas <br>
$texto = nl2br($texto);

echo $texto;

Below is the complete script. I made some html changes to the file index1.php and entered the javascript at the end of it. The code is commented.

    <div class="results"></div>

    <form id="form-teste" class="form">
        <p>
            <label>Número de testes: </label>
        </p>
        <select name="ntestes">
            <option value="0">0</option>
            <option value="1"selected>1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
        </select>
        <input type="button" name="submit" class="execute" value="Executar">
        <a href="log/" class="btn" target="_blank">Visualizar Logs</a>
    </form>

 <script type="text/javascript">

    var finish = false;

    // conexão com o servidor
    const httpObj = (callback, url, params) => {

        let req = new XMLHttpRequest();

        req.addEventListener('readystatechange', () => {

            if(req.readyState === 4 && req.status === 200)
                callback(true, req.responseText);
            else 
                callback(false, req.responseText);
        });

        req.open('POST', url);
        req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        req.send(params);
    }

    // variaveis HTML (formulario e a div results)
    const form = document.querySelector('#form-teste');
    const res  = document.querySelector('.results');

    // quando o formulario fo submetido...
    form.submit.addEventListener('click', e => {

        e.preventDefault();
        finish = false;

        httpObj((status, result)=>{

            if(status) finish = true;

        }, 'http://ssie.com.br:8006/speedtest/shell_test.php', `nTestes=${form.ntestes.value}&submit=executar`);
    //      ^^ URL do script que será executado em php ----------------- ^^ dados do formulario via POST

        let timer = setInterval(() => {

            httpObj((status, result)=>{

                if(status) res.textContent = result;
                if(finish) clearInterval(timer);

            }, 'http://ssie.com.br:8006/speedtest/result_list.php', ``);
    //          ^^ URL do script que atualizará os testes na div results

        }, 2000); // atualiza a cada 2 segundos

    });

 </script>
  • Opa, sorry for the delay in returning, I checked your answer already, but I did not have time to apply the result. I did as you passed, and it actually worked and it didn’t work. The result now there is no line break, it appears the tag in the results <br />. Another detail is that when selecting the quantity '0' it does not return the last executed result but runs the test again.

  • The day after you sent me the answer I had already achieved the solution, but even so I will be applying your answer as sure, because it will help other people as well. Thank you for taking the time to help me.

  • @Roohmaearly quiet friend! Thanks for the validation! Hug!

  • @Roohmacedo AHHH! I didn’t know that the "0" was to return the last result.

  • @Roohmacedo yes... always has some bugs to fix. It is that as I had no way to make the test, I did kind of in the "olhômetro".... rsrsrs.... Valeu man!

Browser other questions tagged

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