Home > database >  How to Insert Array Value from Ajax into Google App Script Spreadsheet
How to Insert Array Value from Ajax into Google App Script Spreadsheet

Time:09-15

I create form in my Wordpress Website.

And then, I'm using bootstrap multiselect to make many checkbox inside select option field. So yeah, I put like wp_enqueue_script and style for bootstrap multiselect. Working good.

Actually, the data can still added but only one value that inserted into spreadsheet.

That means, only index of 0 that inserted into spreadsheet. I want all of value that user checked inside one cell.

I'm already experiment for hours, but still not fixed. I'm already using join(", ") so maybe I all value can inserted using comma separated value (not working). Oh, maybe I'm using $.each() and append(), still not working.

Here is my code:

    <form >
    <div > <div id="nus_event_form_alerts"></div>
    <div >
                            <select name="facultyInterest"  id="facultyInterest"  multiple="multiple">
                                <option value="College of Design and Engineering">College of Design and Engineering</option>
                                <option value="Faculty of Arts and Social Sciences">Faculty of Arts and Social Sciences</option>
                                <option value="Faculty of Dentistry">Faculty of Dentistry</option>
                                <option value="Faculty of Law">Faculty of Law</option>
                                <option value="Faculty of Science">Faculty of Science</option>
                                <option value="Institute of Systems Science">Institute of Systems Science</option>
                                <br /><br />
                            </select>
                        </div>
    <div >
                                <input type="submit" name="submit"  id="submitBtn" style="color: white">
                                <div >
                                    <button type="button" id="loadingBtn" >
                                        <div ><div></div><div></div><div></div><div></div></div>
                                    </button>
                                </div>
                        </div>
    
    </div>
</form>

and then this is my ajax javascript:

$(document).ready(function(){
           
            $('#facultyInterest').multiselect({
                includeSelectAllOption: true,
                nonSelectedText:'School/Faculty/College of interest'
            });

            $('.nus-event-form').validate({
                ignore: [],
                rules:{
                    facultyInterest: "required"
                },
                messages:{
                    facultyInterest:{
                        required: 'Mohon masukkan sekolah/fakultas/kampus yang diminati!'
                    }
                },
                errorPlacement: function(error, element) {
                    if (element.hasClass('multiselect')) {
                        error.insertAfter(element.next('.btn-group'))
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(){
             
                    var data = $('.nus-event-form').serializeArray();
         
                    $.ajax({
                        url: 'https://script.google.com/macros/s/key/exec',
                        data: data,
                        type: 'POST',
                        success: function(response){
                            $("#submitBtn").css("display", "none");
                            $("#loadingBtn").css("display", "block");
                            
                            var json = JSON.stringify(response.result);
                            
                            setTimeout( () => {
                                $("#submitBtn").css("display", "block");
                                $("#loadingBtn").css("display", "none");

                                if(json.slice(1, -1) == "success"){
                                    $("#nus_event_form_alerts").html("<div class='alert alert-success'>Terima kasih! Formulir Anda sudah diterima dan akan di follow up dalam waktu 24 jam.</div>");
                                    $(".nus-event-form")[0].reset();
                                }else{
                                    $("#nus_event_form_alerts").html("<div class='alert alert-danger'>Formulir gagal diterima!</div>")
                                }
                            }, 5000);
                        }
                    });
                }
            });


        });

this is my app script code:

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow()   1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

I hope I can get the help, I'm really frustrated because the code not working to what I want. Thank you developers.

update:

I insert this code:

var data = $('.nus-event-form').serializeArray().map((e)=>{
                        return e.value;
                    }).join(', ');

But I don't understand why still not inserted inside google spreadsheet.

CodePudding user response:

I'm already fixing the code. For developers that have same problem like mine, you can check this url: Using select multiple to send multiple values to google sheets using google apps script

So, the problem is from App Scripts code.

My code like this before:

return header === 'timestamp' ? new Date() : e.parameter[header]

And then, I just add join functions: join();

return header === 'timestamp' ? new Date() : e.parameters[header].join(",");

Here is my full apps script code:

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow()   1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameters[header].join(",");
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

After that, in your javascript using serialize();

Here is my full code:

submitHandler: function(){
             
                    var data = $('.nus-event-form').serialize();
             
                    $.ajax({
                        url: 'https://script.google.com/macros/s/key/exec',
                        data: data,
                        type: 'POST',
                        success: function(response){
                            $("#submitBtn").css("display", "none");
                            $("#loadingBtn").css("display", "block");
                            
                            var json = JSON.stringify(response.result);
                            
                            setTimeout( () => {
                                $("#submitBtn").css("display", "block");
                                $("#loadingBtn").css("display", "none");

                                if(json.slice(1, -1) == "success"){
                                    $("#nus_event_form_alerts").html("<div class='alert alert-success'>Anda telah berhasil mendaftar untuk Event NUS Postgraduate by Coursework Fair 2022 (PGCF 2022). Silahkan cek Email Anda! Kami akan mengirimkan pengingat dan pembaruan menjelang acara dan detail login Anda satu hari sebelum acara (yaitu 3 Okt 2022).</div>");
                                    $(".nus-event-form")[0].reset();
                                }else{
                                    $("#nus_event_form_alerts").html("<div class='alert alert-danger'>Formulir gagal diterima!</div>")
                                }
                            }, 5000);
                        }
                    });
                }

Happy coding!

  • Related