Loading MySql data with php and ajax

1

First what I have done: On the web I upload a file.csv to the server and then upload it to a table mysql .

What I need: Once the data is already in the table, process it.

As the data is a lot, sometimes my idea is the following (it did not work for me and for now what is executed is done with POST forms and methods and the page is blank until the process finishes, the tab of the browser does not show load image or something similar, so it seems that nothing is running, but if you monitor the process mysql , the data is being processed with SP() MySql ):

  • Link or button.

  • When you click on it, do not reload the page, and call below with ajax another php that only executes a stored procedure that manipulates and processes the data.

  • Once you have clicked, while executing the above (2), show a load gif image or a message that the data is being processed (so that page is not blank 5 or more minutes ).

  • When the processing of the data is finished, change the message or image of the processing by "Upload made" or display errors.

  • The source code is:

    <?
    session_start();
    require "comun.inc";
    ini_set('memory_limit', '256M');
    set_time_limit(0);
    
    
    $objetoWeb= new WEBPanel();
    $objetoWeb->cabeceraTemplate();//cabecera template
    $objetoWeb->tituloModulo('DATOS NUEVOS');//Titulo del modulo
    //$objetoWeb->moduloFiltro($_SERVER['SCRIPT_FILENAME']);
    $menu = new menuLite( $objDb, $_SESSION["NIVEL_DE_ACCESO"], "skin-web.css" );
    $menu->creaMenu();
    $objStyle = new styleDatos();
    $rutaCalendar = "../../clases/web/calendario_web/";
    echo "<BR><BR>";
    
    $conexion = conectar_bd();
    $error="";
    
    ?>
    <html>
        <head>
            <link rel="stylesheet" href="estilos1.css" type="text/css">
            <script language="JavaScript" src="overlib.js"></script>
            <DIV ID="overDiv" STYLE="position:absolute; visibility:hide;z-index:1;"></DIV>
        </head>
    <body>
        <br>
        <font size="2"><b>El archivo debe estar en formato .csv(texto plano) separado por ";" y este es el formato que debe contener:</b></font><br/>
        <br>
        <table>
            <tr>
                <td><img src="img/tablacert.jpg"></td>
            </tr>
            <tr>
                <td>
                    <br><br>
                    <b style='color:#0000ff;'>
                        <?=utf8_decode("- El orden de las columnas es importante(debe ser el mismo), la subida del archivo omite en la carga, la 1° línea correspondiente a los titulos de columnas, los cuales deben estar en el archivo.")?>
                    </b><br><br>
                    <b>
                        - Fechas en formato YYYYmmdd.<br><br>
                        - Numeros enteros sin puntos ni coma.<br><br>
                        - Fecha de castigo indicada en YYYYmmdd.<br><br>
                        - Si el archivo original es un excel que se pasa a .csv, antes de hacerlo se debe reemplazar en toda la data ";" por nada o por un espacio " ".
                    </b>
                </td>
            </tr>
        </table>
        <br />
    
        <form name="frm" action="sube_certificados.php" method="POST" enctype="multipart/form-data">
            <table>
                <tr class="td">
                    <td>
                        <div><b>Carga de Certificados de Acsa:</b></div>
                    </td>
                </tr>
            </table>
    
            <br><br>
            <input type='hidden' name='flag' value='Enviado'>
            <input name="file" type="file" />
            <input class="button" type="submit" name="guardar" value="Guardar" />
        </form>
    </body>
    
    <?
    if(isset($_POST['flag']))
    {
    
        $varArNombre= (isset($HTTP_POST_FILES['file'])?$HTTP_POST_FILES['file']['name']:'');
        $varArContenido= (isset($HTTP_POST_FILES['file'])?$HTTP_POST_FILES['file']['tmp_name']:'');
        if($varArNombre!=''){
            if(!move_uploaded_file($varArContenido,"archivos/".$varArNombre)) echo "error al subir el archivo";
        }
    
    
        #validación del archivo
        $archivo = "archivos/".$varArNombre;
        $fp = fopen($archivo,'r');
        error_reporting(E_ALL ^ E_NOTICE);
        $cont = 0;
        $retorno_error="";
        $error='NO';
    
        #leemos el archivo
        $i=1;
    
        mysql_query("TRUNCATE TABLE webcertificadosdb.CERTIFICADOS_TBl;");
    
        while ($linea= fgets($fp,1024)){
            if($i>1)
            {
                $arrCampos = explode(';',$linea);
    
                $ic          = $arrCampos[0]*1;
                $folio       = $arrCampos[1]*1;
                $nsap        = $arrCampos[2]*1;
                $n_doc       = trim($arrCampos[3]);
                $emision     = $arrCampos[4]*1;
                $vencimiento = $arrCampos[5]*1;
                $valor_doc   = $arrCampos[6]*1;
                $rut         = trim($arrCampos[7]);
                $razon       = trim($arrCampos[8]);
                $causal      = trim($arrCampos[9]);
                $motivo      = $arrCampos[10]*1;
                $fech_cast   = $arrCampos[11]*1;
    
                $sqli = "
                    INSERT INTO webcertificadosdb.CERTIFICADOS_TBl
                    SELECT
                    '$rut',
                    '$ic',
                    '$nsap',
                    '$valor_doc',
                    '$vencimiento',
                    '$n_doc',
                    '$motivo',
                    '$causal',
                    '$folio',
                    DATE_FORMAT('$fech_cast','%Y-%m-%d'),
                    '$razon',
                    '$emision';   ";
                mysql_query($sqli)or die("Error al insertar datos a tabla de certificados : CERTIFICADOS_TBl.\n".mysql_error()."\n".$sqli);
            }
            $i++;
        }
        fclose($fp);    
        echo "<br><b>Se subieron : ".( $i >= 3 ? ($i-2): 0 )." registros.</b><br/>";
    
        if( $i >= 3 )
        {
        echo "
        <form name='frmSp' action='sube_certificados.php' method='POST'>
            <input class='button' type='submit' name='Procesar' value='Procesar Carga' />
        </form>";
        }
    
    
        if (file_exists($archivo)) unlink($archivo);
    } // fin del if
    
    if(isset($_POST['Procesar']))
    {   
        echo"<div id='imgcarga'> </div>";
        ?>
        <script>
          document.getElementById("imgcarga").innerHTML = "<img src='img/loading.gif'  async='async'>";
        </script>
        <?php
    
        mysql_query("CALL webcertificadosdb.CargaTotalCertificados();") or die("Se produjo un error durante el procesamiento de los datos subidos");
    
        ?>
        <script>
          document.getElementById("imgcarga").innerHTML = " ";
        </script>
        <?php
    
        echo "<br><br><b>Certificados procesados</b>";
    }
    
    
    $objetoWeb->pieTemplate();
    $objStyle->iFrameCalendar($rutaCalendar);
    desconectar_bd();
    ?>
    </html>
    
        
    asked by Eduardo O 12.04.2018 в 22:46
    source

    0 answers