Refresh Div HTML PHP Javascript

4

I'm having some problems updating a div without updating the entire page. Here is the code:

<div class="main" align="justify">
     <div id="mensagens">
          <?php echo file_get_contents('arquivo.txt'); ?>
     </div>
...

I've thought about creating a "frame" - I'm not sure if that would be the name - and use "meta refresh" to update within it.

My question is: How to update this Div using PHP or Javascript? And if possible, how would you update this Div whenever there is a change in the ".txt file"?

Update

The ".txt file" is updated normally:

$texto = htmlspecialchars($_POST['text']);
$string = $texto . "\n";
$fp = fopen('arquivo.txt', 'a');
$fw = fwrite($fp, $string);
fclose($fp);
    
asked by anonymous 19.11.2015 / 22:33

2 answers

1

Try this:

index.php

<!DOCTYPE HTML>
<html>
    <head>
    <meta charset="UTF-8">
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><scriptsrc="script.js"></script>
</head>
<body>
    <label>Dados:</label>
    <input name="text" id="text" value="#Teste"><br>
    <br>
    <button type="submit" id="btn_submit">Confirma</button>
    <div id="resultado"></div>
</body>
</html>

script.js

$(function () {
    $('#btn_submit').click(function () {
        grava();
    });
    $.post("grava.php", {},
    function (resp) {
        $('#resultado').html(resp);
    });    
});

function grava() {
    $.post("grava.php", {
        text: $("#text").val()
    },
    function (resp) {
        $('#resultado').html(resp);
    });
}

grava.php

<?php

if (!empty($_POST['text'])) {
    $texto = htmlspecialchars($_POST['text']);
    $string = $texto . ";\n";
    $fp = fopen('arquivo.txt', 'a');
    $fw = fwrite($fp, $string);
    fclose($fp);
}
echo file_get_contents('arquivo.txt');

OBS: Give write permission to the directory.

    
21.09.2016 / 23:28
0

Uses setInterval() to load file with time interval.

Html:

<div id="rg">
    Texto desatualizado!
</div>

JQuery:

    <script>
        setInterval(function () {
            $.ajax({
                method: "GET", //GET OU POST
                url: "/text.txt" //LOCAL DO ARQUIVO

            }).done(function (answer) {
                $('#rg').html(answer);//Executa se tiver sucesso

            }).fail(function (jqXHR, textStatus) {
                console.log("Request search failed: " + textStatus); //executa se falhar 
            });
        }, 2000); // Tempo para cada execução
    </script>

The .html(answer); will put the information received between the respective opening and closing tags and

    
01.01.2017 / 05:56