Export data csv with PHP, Jquery

0

The HTML code is:

        <input type="text" class="form-control" id="from_date" name="from_date" aria-describedby="basic-addon3">
    <div class="input-group mb-3">
        <input type="text" class="form-control" id="to_date"    name="to_date" aria-describedby="basic-addon3">
    </div>

    <input type="button" class="btn btn-primary input-group mb-3 margin" name="buscar" id="buscar" value="Buscar"/>

<input type="button" class="btn btn-success mb-3 margin" name="export" id ="export" value="Export CSV"/>

I have the following Script that returns the data of the database:

<script>

$(document).ready(function(){
  var date_input=$('input[name="from_date"]'); 
  var options={
    format: 'yyyy-mm-dd',
    todayHighlight: true,
    autoclose: true,
  };
  date_input.datepicker(options);
  var date_input=$('input[name="to_date"]');
  var options={
    format: 'yyyy-mm-dd',
    todayHighlight: true,
    autoclose: true,
  };
  date_input.datepicker(options);

      $('#buscar').click(function(){
        var from_date = $('#from_date').val();
        var to_date = $('#to_date').val();
        var numero_serie = $('#numero_serie').val();
      if(from_date != '' && to_date != '')
      {

        $.ajax({
          url:'process.php',
          method:"POST",
          data:{from_date:from_date, to_date:to_date, numero_serie:numero_serie},
           success:function(data)
          {

            $('#datos').html(data);
          }
        });
      }
      else
      {
        alert("Selecciona una fecha");
      }
});
      $('#export').click(function(){
        $.post("export.php"),{
        var from_date = $('#from_date').val();
        var to_date = $('#to_date').val();
        var numero_serie = $('#numero_serie').val();}

});
}); 
</script>

The export.php file is:     

if(isset($_POST["from_date"],$_POST["to_date"],$_POST["numero_serie"]))
{
$connect = mysqli_connect("localhost:3306","usuario","password","bd");
$filename = date('Ymd').'-'.$_POST["numero_serie"].'.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);
$output = fopen('php://output','w');
fputcsv($output, array('Fecha', 'Hora', 'WA', 'Estado', 'Numero_serie'));

$query="SELECT * FROM tabla WHERE fecha_reg BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."' AND numero_serie = '".$_POST["numero_serie"]."'";

$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result))
{
    fputcsv($output, $row, ";");
}
fclose($output);
exit;
}

?>

The search by dates of the records by ajax works correctly, but I want to export them to CSV, how do I pass the parameters with $ ('# export'). click (function () {to export.php so that it appears to me the file save dialog window ?, I read that with ajax is not the correct way to do it.

What would be the correct way to do this?

Thank you.

    
asked by F.Sola 06.03.2018 в 11:56
source

2 answers

1

As you say the correct way to do the download would not be through an ajax, you have to redirect to the function in php that will take care of the download of the document:

$('#export').click(function(){
    var from_date    = $('#from_date').val();
    var to_date      = $('#to_date').val();
    var numero_serie = $('#numero_serie').val();

    document.location.href = 'export.php'+
                             '?from_date='+JSON.stringify(from_date)+
                             '&to_date='+JSON.stringify(to_date)+
                             '&numero_serie='+numero_serie;
});

The code in PHP would be more or less like this:

<?php 
    if(isset($_GET["from_date"],$_GET["to_date"],$_GET["numero_serie"])) {

        $from_date  = json_decode($_GET["from_date"]);
        $to_date        = json_decode($_GET["to_date"]);
        $numero_serie   = $_GET["numero_serie"];

        $connect = mysqli_connect("localhost:3306","usuario","password","bd");
        $query="SELECT * FROM tabla WHERE fecha_reg BETWEEN '".$from_date."' AND '".$to_date."' AND numero_serie = '".$numero_serie."'";
        $result = mysqli_query($connect, $query);

        $output = fopen('php://output','w');
        fputcsv($output, array('Fecha', 'Hora', 'WA', 'Estado', 'Numero_serie'));

        while($row = mysqli_fetch_assoc($result))
            fputcsv($output, $row, ";");

        fclose($output);
        $filename = date('Ymd').'-'.$numero_serie.'.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename='.$filename);
        print($output);
    }
?>

Tell me if it works for you. According to my own experience the name of the file should not have too many characters since it may not be downloaded to you.

    
answered by 07.03.2018 / 13:58
source
0

At the moment what I need is working for me this way;

 $('#export').click(function(){
    $.post("export.php"),{
    var from_date = $('#from_date').val();
    var to_date = $('#to_date').val();
    var numero_serie = $('#numero_serie').val()  
 $.ajax({
          url:'export.php',
          method:"POST",
          data:{from_date:from_date, to_date:to_date,  numero_serie:numero_serie},
           success:function(data)
          {
            var filename = numero_serie+'_'+from_date+'_'+to_date+'.csv';
            var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(data);
            var downloadLink = document.createElement("a");
            downloadLink.href = uri;
            downloadLink.download = filename;

            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
          }
            });
;} 
    
answered by 07.03.2018 в 16:12