How to bring table with data when returning from an Insert

Asked

Viewed 1,603 times

9

I edited the question of the post because I think it is the most logical solution to the issue. I have a page with 3 tabs and in one of these I upload files to my hosting and send the necessary information to the database, mount an html table with the records I just registered to display to the user but the page is not updated, I would like to be able to return to the page to show a table with the registered data, always being updated every new entry and if possible in the origin tab of the registration, I could not find nor example that could help me.

Something like this post: https://stackoverflow.com/questions/16707648/using-jquery-ajax-to-retrieve-data-from-mysql

What I have is this on the upload return:

header('Content-Type: application/json');
echo json_encode($aretorno);

And TAB’s name is:

<div class="tab-pane" id="panel-2">

Script that uploads and returns:

    // INICIA O UPLOADO DO ARQUIVO
$(document).ready(function() {

    function getDoc(frame) {
        var doc = null;

        // IE8 cascading access check
        try {
            if (frame.contentWindow) {
                doc = frame.contentWindow.document;
            }
        } catch (err) {}

        if (doc) { // successful getting content
            return doc;
        }

        try { // simply checking may throw in ie8 under ssl or mismatched protocol
            doc = frame.contentDocument ? frame.contentDocument : frame.document;
        } catch (err) {
            // last attempt
            doc = frame.document;
        }
        return doc;
    }

    $("#multiform").submit(function(e) {
        $("#multi-msg").html('<img src="../_imagens/ajax-loader.gif" alt="Enviando..." />');

        var formObj = $(this);
        var formURL = formObj.attr("action");

        if (window.FormData !== undefined) // for HTML5 browsers
        //  if(false)
        {

            var formData = new FormData(this);
            $.ajax({
                url: formURL,
                type: 'POST',
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
                success: function(data, textStatus, jqXHR) {
                    $("#multi-msg").html('<pre><code>' + data + '</code></pre>');                       
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $("#multi-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
                }
            });
            e.preventDefault();
            e.unbind();
        } else //for olden browsers
        {
            //generate a random id
            var iframeId = 'unique' + (new Date().getTime());

            //create an empty iframe
            var iframe = $('<iframe src="javascript:false;" name="' + iframeId + '" />');

            //hide it
            iframe.hide();

            //set form target to iframe
            formObj.attr('target', iframeId);

            //Add iframe to body
            iframe.appendTo('body');
            iframe.load(function(e) {
                var doc = getDoc(iframe[0]);
                var docRoot = doc.body ? doc.body : doc.documentElement;
                var data = docRoot.innerHTML;
                $("#multi-msg").html('<pre><code>' + data + '</code></pre>');
            });
        }
    });
    $("#multi-post").click(function() {

        $("#multiform").submit();
    });
});

PHP inserting data into BD:

require_once("../_connections/pcon.php");
require_once("../_comp/internos/funcoes.php");

//Array que irá retornar o status da execução do script (JSON)
$aretorno = array();    
$aretorno["msg"] = "";
$aretorno["status"] = "";

@$conn = new mysqli($hostname_pcon, $username_pcon, $password_pcon, $database_pcon);

// Checar conexão
if ($conn->connect_errno) {
    $aretorno["msg"] = "Conexão ao banco de dados falhou.";
    $aretorno["status"] = "ERRO";
    header('Content-Type: application/json');
    echo json_encode($aretorno);
    exit;
}

if (!$conn->set_charset("utf8")) {
    $aretorno = array();    
    $aretorno = "Erro ao carregar conjunto de caracteres utf8.";
    header('Content-Type: application/json');
    echo json_encode($aretorno);
    exit;
}

// RESGATE DAS VARIÁVEIS
$IdContrato = $_POST["IdContrato"];
$Observacao = $_POST["Observacao"]; 
$DataHora = date('Y-m-d H:i:s');

// REGISTRO DO LOG
$dataAgora = date('d/m/Y');
$hora = date("H:i:s"); 
$partes = explode("/", $dataAgora);
$dia = $partes[0];
$mes = $partes[1];
$ano = $partes[2];

// DIRETÓRIO
$diretorio = 'upload/'; 

if (!empty($_FILES)) {
    $ArquivoTemporario = $_FILES['arquivo']['tmp_name'];
    $NomeArquivo = $_FILES['arquivo']['name'];  
    $CaminhoAnexo = dirname(__FILE__) . '/' . $diretorio;
    $targetFile = rtrim($CaminhoAnexo,'/') . '/' . $_FILES['arquivo']['name'];
    $TipoArquivo = strtolower(pathinfo($NomeArquivo, PATHINFO_EXTENSION));

    $Caminho = $diretorio; 

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png','pdf','doc','docx','xls','xlsx'); // File extensions
    $fileParts = pathinfo($_FILES['arquivo']['name']);

    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($ArquivoTemporario,$targetFile);
    } else {
        echo 'Tipo de Arquivo invalido';
        exit;
    }
}

// COMPONDO O LOG
$Log = $_SESSION['u_login']."_".$dia.$mes.$ano."_".$hora;
$Usuario = 'Valter';

$sql = "INSERT INTO gerDoctoContrato ( IdContrato, NomeArquivo, TipoArquivo, CaminhoAnexo, Usuario, DataHora, Observacao, Log ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)";

// Preparar os dados:
// i corresponde a uma variável de tipo inteiro
// d corresponde a uma variável de tipo double
// s corresponde a uma variável de tipo string
// b scorresponde a uma variável que contém dados para um blob e enviará em pacotes

if($stmt = $conn->prepare($sql) ){

    $stmt->bind_param(
        "ssssssss",

    // RESGATE DAS VARIÁVEIS        
    $IdContrato,
    $NomeArquivo,
    $TipoArquivo,               
    $Caminho,
    $Usuario,
    $DataHora,
    $Observacao,    
    $Log        
    );      

    // DESLIGA O AUTO COMMIT
    // $conn->autocommit(false);

    // INSERINDO REGISTRO NO BD
    if ($stmt->execute()) { 
        $aretorno["msg"] = "Registro inserido com sucesso.";
    } else {
        $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados:". $stmt->error ." Verifique";
        $aretorno["status"] = "ERRO";
    }

} else {
    $aretorno["msg"] = "Ocorreu um erro na preparação dos dados: "  . $stmt->error . ". Verifique.";
    $aretorno["status"] = "ERRO";
}

// FECHA CONEXÃO COM BD
$conn->close();

//retornando o status / mensagem da execução
header('Content-Type: application/json');
echo json_encode($aretorno);

I don’t know exactly what to post to exemplify what I already have.

1 answer

11


Try something like this, on date, try to parse: var saida = jQuery.parseJSON(data); It takes the output of the status, and makes a query in the database bringing the data in an array, in this array brings the collection via JSON and returns it mounting the table:

function getLines(saida) {
    var html ='';
    for (var i in saida.collection) {
                html += "<tr>" +
                          "<td>" + saida.collection[i].idContrato + "</td>" + 
                          "<td>" + saida.collection[i].NomeArquivo + "</td>" + 
                          "<td>" + saida.collection[i].tipoArquivo + "</td>" + 
                          "<td>" + saida.collection[i].DataHora + "</td>" +
                        "</tr>";
    }
 return html;
}

function getHeader() {
    var html = "<tr>" +
                 "<td>ID</td>" + 
                 "<td>Arquivo</td>" + 
                 "<td>Tipo</td>" + 
                 "<td>Período</td>" +
                "</tr>";
 return html;
}

function getTable(saida) {
    if (saida.status == 1) {
        var tabela = ["<table width=\"100%\">",
                      getHeader(),
                      getLines(saida),
                     "</table>"].join("");
       $('#panel-2').html(tabela);
    }
}

$.ajax({ 
         url: formURL,
         type: 'POST',
         data: formData,
         mimeType: "multipart/form-data",
         contentType: false,
         cache: false,
         processData: false,
         success: function(data, textStatus, jqXHR) {
                  $("#multi-msg").html('<pre><code>' + data + '</code></pre>'); 
                  //console.log(data);
                  getTable(jQuery.parseJSON(data));           
                  },
         error: function(jqXHR, textStatus, errorThrown) {
                    $("#multi-msg").html('<pre><code class="prettyprint">' +
                                         'AJAX Request Failed' +
                                         '<br/> textStatus=' +
                                         textStatus +
                                         ', errorThrown=' +
                                            errorThrown +
                                         '</code></pre>');
                }
});

In PHP, you bring the query data as in the example below:

$sql = "SELECT * FROM gerDoctoContrato where 1 order by Tipo Arquivo ASC, DataHora DESC, NomeArquivo ASC";
$result = mysqli_query($conn, $sql);
$data = $stmt->fetch_all($result, MYSQLI_ASSOC);
    if ($stmt->execute()) { 
        $aretorno["msg"] = "Registro inserido com sucesso.";
        $aretorno["status"] = "1";
        $aretorno["collection"] = $data;
    } else {
        $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados:". $stmt->error ." Verifique";
        $aretorno["status"] = "ERRO";
        $aretorno["collection"] = null;
    }

Browser other questions tagged

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