Home > other >  How can I display the number of free places for an event using google script and javascript
How can I display the number of free places for an event using google script and javascript

Time:09-16

I am creating a registration form for an event and I would like that every time the website is loaded, the number of free spots is calculated from a Google Sheet document and the value is displayed on the form, that has been programmed in html/javascript.

This is my Code.gs

function updateSpots(){
  var nospots
  var url="<MY URL>";
  var ss= SpreadsheetApp.openByUrl(url);
  var ws=ss.getSheetByName("2022-2023");
  var range = ws.getDataRange();
  var values = range.getValues();
  nospots = values.length;
  return nospots;
}

My index.html

<div>
<p id="places"></p>
<script>
  var booked_spots = updateSpots();
  //var booked_spots = google.script.run.updateSpots(); I tried this before... did not work
  console.log(booked_spots)
  if(booked_spots < 20)
  {
    document.getElementById("places").innerHTML = (20 - booked_spots);
  }
  else
  {
    document.getElementById("places").innerHTML = "There are no longer places available for this event";
  }
</script>
</div>   

I get this error on the console:

VM295:2 Uncaught ReferenceError: updateSpots is not defined
    at <anonymous>:2:22
    at qh (2924413381-mae_html_user_bin_i18n_mae_html_user.js:128:336)
    at 2924413381-mae_html_user_bin_i18n_mae_html_user.js:25:132
    at Ld (2924413381-mae_html_user_bin_i18n_mae_html_user.js:56:477)
    at a (2924413381-mae_html_user_bin_i18n_mae_html_user.js:54:52)

And also, on the website the number of free spots do not appear.

I am new to this, so any help is very much appreciated. :)

CodePudding user response:

To call the server function updateSpots you need to do the following. It is just my personal preference to always use Immediately-Invoked Function Expressions to insure variable are retained in the local scope of the IIFE. I avoid global variables as much as possible.

<script>
  (function () {
      google.script.run.withSuccessHandler(
        function(booked_spots) {
          if(booked_spots < 20)  {
            document.getElementById("places").innerHTML = (20 - booked_spots);
          }
          else {
            document.getElementById("places").innerHTML = "There are no longer places available for this event";
          }
        }
      ).updateSpots();
    }
  )();
</script>

Reference

  • Related