-1

When i'm hitting the export button, i would like to download data that I've obtained from my php file. The only problem is: when i'm hitting the button the file csv file is generated but it says: file could not be opened, Failed-forbidden

HTML CODE:

<form id="form" method="POST"> 
     <button id="export" name="export_btn" onclick="export_data();"><i class="fa fa-download" aria-hidden="true"></i> Export To CSV-File</button> <!--Export Btn: genereerd een csv file-->
</form>

JavaScript Code:

function export_data(){
        
        event.preventDefault(); //zorgt ervoor dat je pagina niet onnodig herlaad als je op de btn drukt
        
        //deze function zorgt ervoor dat er een array wordt gemaakt van ID's van alle aangevingte checkboxes.
        var checkedIds = $(".chk:checked").map(function() {
            return this.id;
        }).toArray();

        var Arr = JSON.stringify(checkedIds); //giet de array om in een JSON formaat zodat we ermee kunnen werken in PHP
        
        //aan de hand van ajax stuur ik de array door naar "delete_measurement.php"
        $.ajax({
            type: "POST",
            url: "./export_measurement.php",
            data: {arr: Arr},
            
            success: function(data){ //neem de data dat werd gegenereerd in de php file en download het in een csv file.
                var encodedUri = encodeURI(data);
                var link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "airflow.csv");
                document.body.appendChild(link); // Required for FF

                link.click();
                
                //dit werkte nog niet helemaal. Via volgende link had ik mijn vraag gesteld: https://stackoverflow.com/questions/63846465/download-csv-file-by-using-php/63846748?noredirect=1#comment112902528_63846748
            }

        });
    }

PHP CODE - export_measurement.php:

<?php
include_once("./conn.php"); //connectie file includen

$arr = json_decode($_POST['arr']); //array dat werd doorgestuurd vanuit 'insert_data_measurements.php' en gegoten werd in een JSON formaat, gaan decoderen en opslagen in variabele $arr


header('Content-Type: text/csv; charset=utf-8');  
header('Content-Disposition: attachment; filename=airflow.csv'); 

 for($i = 0; $i < sizeof($arr); $i++){ // door alle aangevingte rijen loopen en deze exporteren

      $output = fopen("php://output", "w");
      fputcsv($output, array('ID', 'ID_meting', 'Name_meting', 'Timestamp', 'Sensor_01', 'Sensor_02', 'Sensor_03', 'Sensor_04', 'Sensor_05', 'Sensor_06', 'Sensor_07', 'Sensor_08', 'Sensor_09', 'Sensor_10', 'Sensor_11', 'Sensor_12', 'Sensor_13', 'Sensor_14', 'Sensor_15', 'Sensor_16'));    
      $query = "SELECT * FROM metingen WHERE ID_meting=$arr[$i]";  
      $result = mysqli_query($conn, $query);  
      while($row = mysqli_fetch_assoc($result)) {  
           fputcsv($output, $row);  
      }  
      
}

fclose($output);    
?>
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • oh, wait, you want a "file save" dialog? don't use `$.ajax` – Jaromanda X Sep 11 '20 at 11:49
  • @JaromandaX what can i do instead? – DarkFelcore Sep 11 '20 at 11:51
  • since you need to use the POST method, you'd either need to a) capture the data and use something like the [fileSave](https://github.com/eligrey/FileSaver.js/) library to initiate the download, or b) fake a form submit along with FormData - but then you can't use JSON – Jaromanda X Sep 11 '20 at 11:51
  • @JaromandaX is it possible to edit my code and show me how to do because i really don't know how i can do it – DarkFelcore Sep 11 '20 at 12:01
  • What have you tried to check where this error occurs? I could not find the error string you've mentioned in your code – Nico Haase Sep 28 '20 at 09:17

1 Answers1

2

Since you are doing a POST, you will need to just return the content of the file from your PHP code and in the success event, do this:

var encodedUri = encodeURI(data);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "airflow.csv");
document.body.appendChild(link); // Required for FF

link.click();
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175