Is it possible to send a FORM, generate a CSV and send it to a folder?

0

I have been investigating for a few hours now, and I have not been able to find much useful information.

With which I refer here to see if I can find help.

  • I have a form, that I work with jQuery, with what I have stored all the variables and data there.

  • I want to try to do the following: when sending the form, generate a CSV file that is saved in any folder of the server. With a specific format.

* ¨ I have nothing done, since I have tried to investigate and I have not found much information.

I would appreciate help to know if I could do this in PHP and jQuery.

EDITING WHAT I HAVE TRIED

I created a PHP file:

<?php
    $cod_cliente = ($_POST['cod_cliente']);
    $optica = ($_POST['optica']);
    $fecha = ($_POST['fecha']);
    $tipo = ($_POST['tipo']);

    $lista = array (
        array('Codigo Cliente', 'Cliente', 'Fecha', 'Tipo'),
        array('$cod_cliente', '$optica', '$fecha', '$tipo'),
    );

    $fp = fopen('fichero.csv', 'w');

    foreach ($lista as $campos) {
        fputcsv($fp, $campos);
    }

    fclose($fp);
?>

And within the jQuery of sending the order, this ajax:

  $.ajax({
    type: 'POST',
    url: 'php/generarCsv.php',
    data: {'cod_cliente': cod_cliente,
           'optica': optica,
           'fecha': fecha,
           'tipo': tipoCi}
  })
  .done(function(listas_rep){
    alert('CSV Generado con exito');
  })
  .fail(function(){
    alert('Error al crear el archivo CSV')
  })

I must say, that above that ajax, I have another, which sends me the order to the database. I do not know if it will conflict.

This, right now, does not do me absolutely nothing.

    
asked by Javier Avila Fernandez 30.08.2018 в 11:13
source

1 answer

1

You do not have to quote the variables in the second row. The following code should work:

<?php
$cod_cliente = 'ejemplo cod_cliente';
$optica      = 'ejemplo optica';
$fecha       = 'ejemplo fecha';
$tipo        = 'ejemplo tipo';

$lista = [
    ['Codigo Cliente', 'Cliente', 'Fecha', 'Tipo'],
    [$cod_cliente, $optica, $fecha, $tipo],
];

$fp = fopen('fichero.csv', 'w');

foreach ($lista as $campos) {
    fputcsv($fp, $campos);
}

fclose($fp);

I'm surprised you say you do not write anything, because it works perfectly for me. If removing the quotes like a csv file is not generated it can be caused by another problem such as:

  • That the folder does not have write permission for the user that runs php (e.g. www-data )
  • That the file exists and does not have writing permission
  • That one of the entries in the superglobal $_POST is not being received.

In the latter case, you should check the existence of the variable, for example by doing:

$cod_cliente = isset($_POST['cod_cliente'])? $_POST['cod_cliente'] : 'no especificado' ;
    
answered by 30.08.2018 / 12:34
source