-2

I am a total newbie with AJAX, and i am asking if it's possible to read a CSV file from "file input" and extract data from it and display the data in the same page without sumbiting the form. here is my codes :

index.html :

<!DOCTYPE html>
<html>
<head>
    <title>Choose a CSV File</title>
</head>
<body>
    <h1>Choose a CSV file :</h1>
    <form method="post" action="csv_to_array.php" enctype="multipart/form-data">
        <div>
            <input type="file" name="file" required/>
            <input type="submit" value="Upload CSV Data" />
        </div>
    </form>
    <div>
    <!-- diplaying the data extracted from the csv file -->
    </div>
</body>
</html>

csv_to_array.php :

<?php

if ($_FILES["file"]["error"] > 0) {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {

    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Stored in: " . $_FILES["file"]["tmp_name"]. "<br>";

    $users = array();

    $labels = array('id', 'name', 'age');

    $fh = fopen ($_FILES["file"]["tmp_name"], 'r');
    fgetcsv($fh);

    if ($fh) {
        while (!feof($fh)) {
            $row = fgetcsv($fh, 500, ';');
            $tempRow = array();
            if (isset($row) && is_array($row) && count($row)>0) {
                foreach ($row as $key => $value) {
                    $tempRow[$labels[$key ]] = $value;
                }
                $users[] = $tempRow;
            }
        }
        fclose($fh);
        $numLines = count($users);
    }

    // I want this to be displayed in index.html :
    echo $numLines;
    echo '<table style="border: 1px solid black;">';
    echo '<tr>';
    echo '<td>ID</td>';
    echo '<td>NAME</td>';
    echo '<td>AGE</td>';
    echo '</tr>';
    for ($x=0; $x<$numLines; $x++) {
        echo '<tr>';
        echo '<td>'.$users[$x]['id'].'</td>';
        echo '<td>'.$users[$x]['name'].'</td>';
        echo '<td>'.$users[$x]['age'].'</td>';
        echo '</tr>';
    }
    echo '</table>';

}

?>

Thank you in advance guys!

bboulahdid
  • 329
  • 1
  • 4
  • 14

1 Answers1

0

There are a lot of different way to do that. What I recommend is to use a plugin as Blueimp jquery file upload: https://github.com/blueimp/jQuery-File-Upload

Why is it better to use an already existing Plugin:

  1. Security (we are here speaking about uploading a file, there are some security concerns that you have to take in to consideration)
  2. File size, format, etc / time to upload
  3. Upload progression (progress bar, etc).
  4. Community/support

Example of what you can do:

1 - File upload (CSV only, 10 MB max ...)

    $('#importData').fileupload({
            dataType: 'json',
            autoUpload: true,
            acceptFileTypes: /(\.|\/)(csv)$/i,
            maxFileSize: 10000000 // 10 MB
            [...]
    }).on('fileuploadprogressall', function (e, data) {
            // You can manage your progress here
    }).on('fileuploaddone', function (e, data) {
            // You can now call your ajax file that will take care of the CSV (csv_to_array.php)
            (*)
    });

2 - Once the upload is done (represented by the '*' in the code above)

    $.ajax({ url: './ajax/csv_to_array.php', 
            data: {file_path:file.name, delete_url: file.deleteUrl},
            type: 'post',
            dataType: "json",
            beforeSend: function(xhr){xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");},
            success: function(dataCSVFile) {   
                            // Here in Jquery for example you can display your data
            });

3 - Be careful at your CSV php process, I recommend you to add a lot of different check to be sure of the format of the file that the user will put. (especially if you plan to save the data in your DB).

Regards,

maxime_039
  • 464
  • 8
  • 14