How to return PHP value without having to reload the page?

Asked

Viewed 216 times

-1

At first I found this question Run PHP without updating the entire page, that gave me a notion, but did not help me to solve the problem. It is the following: On the page pag_messages.php all user contacts will be loaded, by clicking on the contact the system will send via Ajax to adminMensagens.php, there she will execute all codes to find/create xml and the like. The problem is in the back, so I tested PHP is working (creating and saving the xml), only I do not know how to go back an "authorization" to the page pag_messages.php run PHP which will load xml. (Just to make it clear that I have a sense of how the Client/Server interaction works). (I tried to make the return of this "authorization" with the php post in adminMensagens.php, but I remembered that I would have to reload the page, but that’s not the focus). (If anyone can help me, it’s urgent to TCC).

Code of pag_messages.php:

        <div id="a" class="contatos"><center>Contatos</center>

            <?php
            foreach ($contatos as $contato):
                if ($contato['estadoContato'] != 'Desativado') {
                    echo '<div id = "contato' . $cont . '" class = "contato" onclick="abrirMensagem(event); ">';
                    if ($contato['nome'] === null) {
                        echo 'vazio';
                    } else {
                        echo '<center>' . $contato['nome'] . '</center>';
                        echo '<img src="fotos/' . $contato['foto'] . '" width="40px" height="40px">';
                        $_SESSION['contato' . $cont] = $contato[$cpfxml];
                    }
                    echo '</div>';
                }
                $cont++;
            endforeach;
            ?>

        </div>
        <div id="b" class="mensagem"><center>Mensagens</center>
            <?PHP
            // tentativa com o Post
            if (isset($_POST['nomeXML'])){       
                $nomearquivo = $_POST['nomeXML'];
                $dom = $_SESSION['dom'];
                $dom->load($nomearquivo);
                $_SESSION['dom'] = null;
                $ver = simplexml_import_dom($dom);
                foreach ($ver as $xml):
                    echo "<center><p>" . $xml->mensagem . "</p></center>";
                endforeach;
            }
            ?>

        </div>
        <div class="enviarMensagem">
            <form>
                <input type="text" name="txtmsg" placeholder="Digite sua mensagem"><input type="submit" value="Enviar" name="btn">
            </form>
        </div>
        <style type="text/css">
            .contatos
            {
                width: 300px;
                height: 600px;
                background-color: blue;
                float: left;
                overflow:auto;
            }
            .contato
            {
                width: 290px;
                height: 100px;
                margin-left:5px;
                background-color: yellow;
                float: left;
            }
            .mensagem
            {
                margin-left:400px;
                width: 600px;
                height: 600px;
                background-color: red;
                overflow:auto;
            }
            .enviarMensagem
            {
                margin-left:400px;
            }

        </style>
        <script>
            function abrirMensagem(event) {
                $.post("adminMensagens.php", {
                    cpfContato: event.target.id, cpflogado: <?php echo $cpf; ?>
                }, function (msg) {
                    $("#teste").html(msg);
                })
            }

        </script>
    </body>
</html>

Page code adminMensagens.php:

header('Content-Type: text/html; charset=utf-8');
require_once 'conexao.php';
require_once 'banco-mensagens.php';
session_start();

// para carregar a mensagem
if ((isset($_POST['cpfContato'])) && (isset($_POST['cpflogado']))) {
    $cpfContato = $_POST['cpfContato'];
    $cpfContato = $_SESSION[$cpfContato];
    $cpflogado = $_POST['cpflogado'];
    // <?xml version="1.0" encoding="UTF-8"
    $dom = new DOMDocument("1.0", "ISO-8859-7");
    lerXML($dom, $conexao, $cpfContato, $cpflogado, $_SESSION['tipoUsuarioLogado']);
    $_SESSION['dom'] = $dom;
    mandarNomeXML($_SESSION['nomeXML']);
}

function mandarNomeXML($nomeXML) {
    $content = http_build_query(array(
        'nomeXML' => $nomeXML,
    ));
    $context = stream_context_create(array(
        'http' => array(
            'method' => 'POST',
            'content' => $content,
        )
    ));
    $result = file_get_contents('pag_mensagens.php', null, $context);
    return $result;
}

Bank code-php messages. (file where the functions are, if necessary):

header('Content-Type: text/html; charset=utf-8');

function listarContatos($conexao, $cpf, $tipo) {
    $contatos = array();
    if ($tipo == 2) {
        $sql = "select * from carregarContatoTec where cpf_cliente_fk = $cpf";
    } else {
        $sql = "select * from carregarContatoCli where cpf_tecnico_fk = $cpf";
    }
    $resultado = mysqli_query($conexao, $sql);
    while ($contato = mysqli_fetch_assoc($resultado)) {
        array_push($contatos, $contato);
    }
    return $contatos;
}

function addMensagem($documento, $mensagem, $cpf_origem) {
    // criar msg
    $msg = $documento->createElement("msg");
    // criar nó data
    $data = date('j/n/Y H:i:s');
    $dataElm = $documento->createElement("data_envio", $data);
    // criar nó origem
    $cpf_origemElm = $documento->createElement("cpf_origem", $cpf_origem);
    // criar nó mensagem (texto)
    $mensagemElm = $documento->createElement("mensagem", $mensagem);

    $msg->appendChild($dataElm);
    $msg->appendChild($cpf_origemElm);
    $msg->appendChild($mensagemElm);
    return $msg;
}

function gerarNomeXML() {
    $dir = "xml_msg";
    $novonome = $dir . "/" . md5(uniqid(time())) . ".xml";
    return $novonome;
}

function lerXML($dom, $conexao, $cpfCli, $cpfTec, $tipo) {
    if ($tipo === 2) {
        $sql = "select caminho_xml as xml from tbl_mensagem where cpf_cliente_fk = $cpfCli and cpf_tecnico_fk = $cpfTec";
    } else {
        $sql = "select caminho_xml as xml from tbl_mensagem where cpf_cliente_fk = $cpfTec and cpf_tecnico_fk = $cpfCli";
    }
    $return = mysqli_query($conexao, $sql);
    $row = mysqli_fetch_array($return, MYSQLI_ASSOC);
    $nomeArquivo = $row["xml"];
    if (!file_exists($nomeArquivo)) {
        $novonome = gerarNomeXML();
        guardarXML($conexao, $novonome, $cpfCli, $cpfTec, $tipo);
        $msg = addMensagem($dom, "Conectados!", null);
        // criando nó principal
        $root = $dom->createElement("mensagens");
        // adiciona a mensagem ao root
        $root->appendChild($msg);
        // adiciona o root ao xml
        $dom->appendChild($root);
        // retirar os espaços em branco
        $dom->preserveWhiteSpace = false;
        // gerar código ??
        $dom->formatOutput = true;
        $_SESSION['nomeXML'] = $novonome;
        $dom->save($novonome);
        return $root;
    } else {
        // carrega o arquivo
        $dom->load($nomeArquivo);
        $_SESSION['nomeXML'] = $nomeArquivo;
        // recupera nó principal
        $root = $dom->documentElement;
        return $root;
    }
}

function guardarXML($conexao, $caminho, $cpfCli, $cpfTec, $tipo) {
    if ($tipo == 2) {
        $sql = "update tbl_mensagem set caminho_xml = '$caminho' where cpf_cliente_fk = $cpfTec and cpf_tecnico_fk = $cpfCli";
    } else {
        $sql = "update tbl_mensagem set caminho_xml = '$caminho' where cpf_cliente_fk = $cpfCli and cpf_tecnico_fk = $cpfTec";
    }
    $resultado = mysqli_query($conexao, $sql);
    return $resultado;
}

  • In pag_messages.php: has a form and also has a function abrirMensagem(event) How is the function triggered? and the form does what? I’m not seeing coherence.

  • The form is now useless, I will use it to send a new message in the future. the function open thinking is executed at Div click.

  • now that I’ve seen there on the foreach, rs

  • And by clicking on the div this function does what it has to do?

  • She sends to adminMensagens.php the login user’s Cpf and the contact that was clicked, there it runs all the lerXML, puts the xml name and the gift in the session, and should return a way to authorize the code that is in the div messages were executed.

  • This function here with me didn’t work, I’m doing another

  • Just a remark, I took the get and put an if to check if $_SESSION['dom'] was empty, then when I click on the div and reload the page, the xml opens, but I have to reload the page...

  • Can this code of the messages div run on another page? It only has Session on it

  • Can, but would have to follow the bank select, otherwise the login user’s Cpf would not appear in adminMensagens.php.

  • Then, the adminMensagens.php page will return to the page.php messages: an "authorization", which would be this authorization, like "sends hot" or some variable that you have there

  • I’ve built an equema, tested it and it’s spinning beauty

  • Could you send me his link on Github so I can try to implement?

Show 7 more comments

1 answer

0

I don’t see how the adminMensagens.php spend a "autorização" to the pag_mensagens.php run a PHP code. You can, by owning this "autorização", invoke another ajax to run this PHP on another page, or even to adminMensagens.php, just make a conditional on her passing the proper parameters. You can also perform all the steps of the adminMensagens.php plus PHP’s div messages

I will post the answer with two requests because it may be necessary for its development. In addition, as said above, it is possible to modify.

Code for pag_messages.php:

    <div id="a" class="contatos"><center>Contatos</center>

        <?php
        foreach ($contatos as $contato):
            if ($contato['estadoContato'] != 'Desativado') {
                echo '<div id = "contato' . $cont . '" class = "contato" onclick="abrirMensagem(event); ">';
                if ($contato['nome'] === null) {
                    echo 'vazio';
                } else {
                    echo '<center>' . $contato['nome'] . '</center>';
                    echo '<img src="fotos/' . $contato['foto'] . '" width="40px" height="40px">';
                    $_SESSION['contato' . $cont] = $contato[$cpfxml];
                }
                echo '</div>';
            }
            $cont++;
        endforeach;
        ?>

    </div>

.........................
.........................

<script language="javascript">

jQuery(document).ready(function(){

    $(function(){
        $('.contato').click(function(){
            //id da div clicada
            var id = $(this).attr('id');

            $.ajax({
                type: "POST",
                url: "adminMensagens.php",
                data: {cpfContato: id, cpflogado: "<?php echo $cpf; ?>"},
                // essa function success será executada se a requisição for feita com sucesso
                success: function(data){
                // coloca o conteúdo retornado da consulta da pagina adminMensagens.php - valor da variavel $nomeXML - na div id="resultado"
                $('#resultado').html(data);

                   /*******envia  para divMensagens.php,
                   pode ser o retorno - valor da variavel $nomeXML - da adminMensagens.php ou o que você quiser,
                   por exemplo uma string; altere postNomeXML: data por postNomeXML: "string"
                   ou uma variavel postNomeXML: variavel ***********************************/

                             $.ajax({
                                url: 'divMensagens.php',
                                type: 'post',
                                data: {
                                   postNomeXML: data
                                },
                                success: function(returnhtml) {
                                    $("#result").append($('</p>').html(returnhtml));
                                }
                            }); 

                },
                error: function(){
                  // essa funcion error será executada caso ocorrer algum erro na requisição
                  $("#resultado").html("Ouve um erro");
                }   
            });

            event.preventDefault();

            return false;

        });
    });
});

</script>

..................
..................

Page code adminMensagens.php:

<?php
......................
......................

 //o que será enviado para a pag_mensagens.php

 echo $nomeXML;

 //que por sua vez vai enviar para a divMensagens.php

?>

Page code divMensagens.php

      <div id="b" class="mensagem"><center>Mensagens</center>
        <?PHP
        // tentativa com o Post
        if (isset($_POST['nomeXML'])){       
            $nomearquivo = $_POST['nomeXML'];
            $dom = $_SESSION['dom'];
            $dom->load($nomearquivo);
            $_SESSION['dom'] = null;
            $ver = simplexml_import_dom($dom);
            foreach ($ver as $xml):
                echo "<center><p>" . $xml->mensagem . "</p></center>";
            endforeach;
        }
        ?>

    </div> 

Unify adminMensagens.php and divMensagens.php use only the first ajax

  • Thank you for your attention, but even so it was not. Unfortunately for the urgency I will leave without Ajax or even I will complete this system in TCC.

  • @Leandro, something is bugging around, with me it works round! you added the library?

  • Yes, I’ll try to review the part I developed, anything warning..

Browser other questions tagged

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