What is the best way to return data in javascript from a downloaded CSV file?

the script should run as follows: the client downloads the CSV file, which then dynamically populates the table with data from the downloaded CSV file.

I can upload a CSV file with a simple form. no problem. I can parse data with PHP on the server side. no problem. I can create an array with a PHP server. no problems.

How the hell am I going back to JavaScript for processing? I thought I could use AJAX, but where would I specify the request?

I thought about using PHP to recursively call the page, but then it loses its asynchrony, which is not entirely normal.

It looks like I missed something simple here.

TIA for your help.

WR!

+4
source share
2 answers

The answer is simple. Download the document asynchronously, and this download call will return some JSON.

Alternatively (and better for large documents), load the document and return the identifier for it, and then call the script with AJAX with that identifier. Thus, you can perform background processing in a large file and return data when ready, or return some kind of wait status when the client waits 5 seconds or so and tries again.

+3
source

If you want to go down the Ajax route, you should create a page (or route) that is specifically designed to receive only CSV data and return it as a json object. Suppose you just need to know an identifier for generating data, you can create csvdata.php that looks for $ _POST ['id'], gets the data for that identifier and returns json_encode(csvArray) data. You probably want to set the mime header('Content-type: application/json'); type header('Content-type: application/json'); This is no different from a script that provides files, for example. All you need to know is what you need to request and what data to send with the request. If you need CSV data on the page, you need to display a script that knows what data to send along with the request. Your template engine should be able to display small dynamic scripts for you. Basically you want to generate a script like

 ... <body> ... <script type="text/javascript"> (function () { var csvid = 1; // Make ajax post to csvid.php with csvid as id }()); </script> </body> 

You would create a script like this where the csvid value is set dynamically (using your selection method to generate html / js). Always use POST to retrieve Ajax data, especially if the data is sensitive and requires session verification. GET in this case will be open to exploits of the json array.

Alternatively, you can just make the array inline without Ajax. So instead of creating ajax request variables, you can simply visualize the script with the array encoded in it.

Template:

 <script type="text/javascript"> (function () { var data = {jsondata}; someNameSpace.someProcessingFunction(data); }()); </script> 

Replaces {jsondata} with json_encode (csvarray);

0
source

Source: https://habr.com/ru/post/1385397/


All Articles