简体   繁体   中英

Parsing CSV file rows for SpreadSheets upload with AJAX

I'm trying to send leads from CSV to Google Sheets with AJAX like this method for send form leads to Google Sheets.

I got it with this code in Gogole App Script but i need this in local to do more actions as delete csv file on finish.

function importCSVFromWeb() {

  var csvUrl = "http://URL/csv/data.csv";
  var csvContent = UrlFetchApp.fetch(csvUrl).getContentText();
  var csvData = Utilities.parseCsv(csvContent);
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var lastRow = range.getLastRow();

  sheet.getRange(lastRow + 1, 1, csvData.length, csvData[0].length).setValues(csvData);
}

This is an example of my data.csv

"4","7","22300","johndoe@example.com","John","Doe","Company SL","666123456","519780151","","","","Instagram"
"6","10","08028","johnsmith@example.com","John","Smith","Company2 SL","666456789","519780151","","","","Facebook"

And this is my AJAX script:

  <script>
    $.ajaxSetup({ cache: false });//disable cache

    $.ajax({
        url: 'csv/data.csv',
        dataType: 'text',
      }).done(successFunction);

    function successFunction(data) {
      var allRows = data.split(/\r?\n|\r/);
      for (var singleRow = 0; singleRow < allRows.length; singleRow++) {

      var rowCells = allRows[singleRow].split(',');
        document.querySelector("#leads-csv").innerHTML += rowCells+"<br/>";

        //alert(rowCells);

        const sheetsURL = 'https://script.google.com/macros/s/XXXXXXXXXXXXXXXXXXXXX/exec'
      const sheets = document.forms['form-csv'] //evento de formulario


            sheets.addEventListener('submit', e => {
                e.preventDefault()

                alert("Se va a insertar en Google Sheets");//once by row

                fetch(sheetsURL, {
                        method: 'POST',
                        body: new FormData(sheets) //Failed to construct FormData!!
                    })
                    .then(response => console.log('Datos guardados en Google Sheets', response))
                    .catch(error => console.error('¡Error, revisa el código superior!', error.message))
            });
      }
    }
    </script>

I have the problem when i trying to create the FormData with CSV rows

Finally I used Guzzle PHP, submitting async forms is much easier than cheating with javascript. Here the little snippet of victory:

    $file = fopen("csv/datos.csv", "r");

    if($file) {

    //If file exists, start read
    while(! feof($file)) {
    $line = fgets($file);

    //Convert complete line to single fields  
    $singleLine = explode(",",$line);  

        $client = new \GuzzleHttp\Client();

        //CSV fields to Google Sheets fields
        $response = $client->request('POST', 'https://script.google.com/macros/s/URL/exec', [
                'form_params' => [
                'nombreDeVariable2' => $singleLine[0],
                'nombreDeVariable3' => $singleLine[1],
                'Zip' => $singleLine[2],
                'email' => $singleLine[3],
                'first_name' => $singleLine[4],
                'last_name' => $singleLine[5],
                'company' => $singleLine[6],
                'phone' => $singleLine[7],
                'elqSiteId' => $singleLine[8],
                'comentarios' => $singleLine[9],
                'gdpr_legitimate_interest' => $singleLine[10],
                'retURL' => $singleLine[11],
                'web' => $singleLine[12],
            ]
        ]);

For post to JSON API y only changed "form_params" for "json", adding API end point and this lines after:

$response = $client->post("/end-point", $options);
echo $response->getBody();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM