0

I would like to be able to export an HTML table to a csv-file. See code below:

HTML table:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8"> 
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
        <script type="text/javascript" src="function.js"> </script>
    </head>
    <body>
        <div class="dataExport">
            <button id='export' type="button">Export</button>
        </div>

        <table class="analysisTable">
            <thead>
                <tr>
                    <th>First name</th>
                    <th>Last name</th>
                    <th>Age</th>
                    <th>Sex</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Jane</td>
                    <td>Doe</td>
                    <td>19</td>
                    <td>F</td>
                <tr>
                    <td>John</td>
                    <td>Doe</td>
                    <td>41</td>
                    <td>M</td>
            </tbody>
        </table>
    </body>
</html>

function.js

$( document ).ready(function() {
    $("#export").click(function(){
        var myTableArray = [];
        $("table.analysisTable tr").each(function() { 
            var arrayOfThisRow = [];
            var tableData = $(this).find('td');
            if (tableData.length > 0) {
                tableData.each(function() { 
                    arrayOfThisRow.push( $(this).text() ); 
                });
                myTableArray.push( arrayOfThisRow );
            }
        });

        $.ajax({
            type: "POST", 
            url: "test_export.php", 
            data: { data: JSON.stringify(myTableArray) }, 
            cache: false,
                response: function(response) {
            console.log("Response: " + response); 
            }, 
            success: function(success) { 
                console.log("Succes: " + success); 
            }, 
            error: function(error){
                console.log("Error: " + error);
            }
        }); 
    });
});

export.php

<?php
    header('Content-Encoding: UTF-8');
    header('Content-Type: application/excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="export.csv"');

    $fp = fopen('php://output', 'w') or die ("fopen failed");

    $array = json_decode($_POST['data']);

    foreach ($array as $row){
        $row = array_map("utf8_decode", $row);
        //print_r ($row);
        fputcsv($fp, $row, ';');
    };

    fclose($fp);
?>

When clicking the button, this code parses the content of the HTML-table correctly, but prints everything to the console:

Succes: Jane;Doe;19;F
John;Doe;41;M

I've already searched here and on other places, but I can't figure out how to convince the php-script to write create a csv-file instead. Is there something I'm doing wrong here?

EDIT: What I would like to achieve in the end is this: I want to get the data from the HTML-table (I guess by using javascript), use this data in PHP for further processing (database-stuff) and download the final result as a csv-file.

Fingashpitzzz
  • 169
  • 4
  • 20
  • Why are you using `AJAX`? Is there any specific reason? You can use normal `GET` request and send your data with querystring parameters? – EhsanT Feb 05 '18 at 13:10
  • I just started using and learning javascript, so I'm following examples I found. – Fingashpitzzz Feb 05 '18 at 13:31
  • [This](https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) question and its answers will help you. You can not do it with simple `AJAX` request. But please take a look at all of the answers and then you will get a clue which of them is the best solution for you... – EhsanT Feb 05 '18 at 13:35
  • None of those answers really do what I want. I need to get the data from the HTML (using javascript I guess), and in the php-script I want to do some processing (database-stuff, not mentioned in my question) and then export the results as csv. – Fingashpitzzz Feb 05 '18 at 14:13
  • 1
    So the answers do exactly what you want to do! Why do you say none of them what you want to do?! It's not that they are the exact answer to your question since the question was different from yours, but you can get some ideas from them. The only limitation you have is if you want to do some validation on server-side(using PHP) and get the results by `AJAX` and if your data has passed the validation, then download the file, which you can not do it in an easy way(although it's also achievable). – EhsanT Feb 05 '18 at 14:19
  • Otherwise you can get the data from `HTML` the same way you are getting right now and then send them directly to you `PHP` file like what I mentioned previously using `window.location.href` and as the `querystring parameters`. In this case, your browser will automatically download the response of your `PHP` file. But if by any chance the `PHP` file generates any errors, then you have to handle it. And that's the part that I said it's not the easy way but it's totally achievable... – EhsanT Feb 05 '18 at 14:22
  • That other answer _would_ help you, if you at least read it until you understand that you can not directly trigger the browser’s download dialog from an AJAX request, because AJAX means _in the background_. Plus, it shows approaches how to handle this situation. So this answer _would_ help you along, if you were willing to accept it as something to first of all broaden your knowledge, resp. fill in the parts that you are missing. Right now however you sound like you were of the “if I can not copy&paste it directly and it works, then I do not consider it an answer” faction ... – CBroe Feb 05 '18 at 14:26
  • Sorry if I sound like that, @CBroe. I just wanted to further clarify what I want to achieve and I didn't really get what EshanT was saying. I am in fact trying to understand what they're doing in those answers :) – Fingashpitzzz Feb 05 '18 at 14:44
  • 1
    The easiest way to do this, would be not to use a background request at all. As @EhsanT said, one way would be to use GET instead of POST parameters (if you can modify the server-side script as well.) If it has to be a POST request, then you can still make one not using AJAX in the background - by creating a form with hidden input fields, and submitting that form via JavaScript (calling the form’s submit method.) Since neither of those two would be background requests, the server response will in that case trigger the download/“safe as …” dialog automatically. – CBroe Feb 05 '18 at 15:02
  • So I guess I was thinking about it all wrong. I followed your tips and got it to work using a form with a POST request. Thanks for your help, @EhsanT and @CBroe! – Fingashpitzzz Feb 08 '18 at 10:42

0 Answers0